What is the Chain of Responsibility pattern?
Why Interviewers Ask This
This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.
Answer
The Chain of Responsibility pattern passes requests along a chain of handlers. Each handler decides to either process the request or pass it to the next handler. HTTP middleware example: abstract class MiddlewareHandler { private MiddlewareHandler next; public MiddlewareHandler setNext(MiddlewareHandler next) { this.next = next; return next; // Enables fluent chaining } protected boolean passToNext(HttpRequest request) { if (next != null) { return next.handle(request); } return false; } public abstract boolean handle(HttpRequest request); } class AuthenticationMiddleware extends MiddlewareHandler { @Override public boolean handle(HttpRequest request) { String token = request.getHeader("Authorization"); if (token == null || !isValid(token)) { System.out.println("AUTH FAILED: 401 Unauthorized"); return false; } System.out.println("AUTH: Authenticated user"); return passToNext(request); } } class RateLimitMiddleware extends MiddlewareHandler { private Map<String, Integer> requestCounts = new HashMap<>(); @Override public boolean handle(HttpRequest request) { String ip = request.getClientIp(); int count = requestCounts.getOrDefault(ip, 0); if (count >= 100) { System.out.println("RATE LIMIT: 429 Too Many Requests"); return false; } requestCounts.put(ip, count + 1); return passToNext(request); } } class LoggingMiddleware extends MiddlewareHandler { @Override public boolean handle(HttpRequest request) { System.out.println("LOG: " + request.getMethod() + " " + request.getPath()); return passToNext(request); } } // Setup chain: MiddlewareHandler auth = new AuthenticationMiddleware(); MiddlewareHandler rateLimit = new RateLimitMiddleware(); MiddlewareHandler logging = new LoggingMiddleware(); auth.setNext(rateLimit).setNext(logging); auth.handle(request); // Auth → RateLimit → Logging. Real examples: Java exception handling, Spring Security filter chain, Node.js Express middleware, Servlet Filters, GUI event bubbling.
Pro Tip
This topic has OOP Concepts-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.