The Chain of Responsibility pattern promotes loose coupling by removing the sender's knowledge of exactly which object will handle its request. The sender only knows about the first handler in the chain; every handler after that is discovered dynamically as the request moves along.
An HTTP request filter chain (authentication, logging, rate limiting) lets each filter decide whether to process the request or pass it along, and new filters can be inserted without modifying the controller that originally received the request.
import java.util.ArrayList;
import java.util.List;
public class FilterChainDemo {
record Request(String user, String path) {}
interface Filter { void doFilter(Request req, Chain chain); }
// The chain only knows "call the next filter"; filters don't know each other
static class Chain {
private final List<Filter> filters = new ArrayList<>();
private int index = 0;
Chain add(Filter f) { filters.add(f); return this; }
void proceed(Request req) {
if (index < filters.size()) filters.get(index++).doFilter(req, this);
else System.out.println("Controller handled " + req.path());
}
}
public static void main(String[] args) {
Filter logging = (req, chain) -> { System.out.println("Log: " + req.path()); chain.proceed(req); };
Filter auth = (req, chain) -> {
if (req.user() == null) System.out.println("401 Unauthorized");
else chain.proceed(req);
};
Filter rateLimit = (req, chain) -> { System.out.println("Rate limit OK"); chain.proceed(req); };
new Chain().add(logging).add(auth).add(rateLimit).proceed(new Request("asha", "/orders"));
new Chain().add(logging).add(auth).add(rateLimit).proceed(new Request(null, "/orders"));
}
}Log: /orders
Rate limit OK
Controller handled /orders
Log: /orders
401 Unauthorized
A concise interview answer is
The sender only ever talks to the first handler in the chain, not to whichever handler eventually processes the request, so the two are decoupled. Because each handler just knows about the next one, I can add, remove, or reorder handlers freely without touching the client code that kicked off the request.
Last updated: 1 November 2026
Previous question: Can you provide an example of when you would use the Chain of Responsibility pattern?
Next question: What are the drawbacks of using the Chain of Responsibility pattern?