Chain of responsibility
Chain of responsibility passes a request along a list of handlers. Each handler decides to handle it, pass it on, or both. The sender does not know which handler will run.
Detailed Explanation
A web request hits authentication, then logging, then routing. Each step is a handler with a next. Servlet filters are this pattern. Logger levels (FINE → INFO → SEVERE) are a chain: the first logger that accepts the level writes, or the event travels up.
A handler's contract should be explicit: exclusive (first match stops) or pipe (every handler may run). Mixing them without a name is a bug. FilterChain.doFilter is a pipe: each filter calls the rest. A support ticket router is exclusive: the first matching team takes it.
You build the chain at composition time: auth.then(log).then(route). Recursion or a loop over a list both work. A list plus an index is easier to debug than linked next fields.
You reach for a chain when several independent policies may apply and you want to add one without editing the others. You reach for a single switch when the set is closed and central. You reach for a decorator when every layer always runs and wraps the same interface.
The cost of a long chain is latency and an unclear path. Log which handler claimed the request. The cost of a handler that forgets to call next is a silent drop. The cost of mutable request objects is handlers that interfere; document who may change what.
Keep handlers small. A handler that does five jobs is a chain hiding in one class.
Name the chain after the decision, not after a framework. AuthThenAuditThenRoute is worse than three types you can reorder in one factory method. Tests should send a request that stops at the first handler and a request that falls through to the last. If you cannot write those two tests, the chain is not a chain yet; it is one procedure cut into methods.
Code Examples
interface Handler {
void handle(String req);
}
class PrefixHandler implements Handler {
private final String prefix;
private final Handler next;
PrefixHandler(String prefix, Handler next) {
this.prefix = prefix;
this.next = next;
}
@Override
public void handle(String req) {
if (req.startsWith(prefix)) {
System.out.println(prefix + " got " + req);
return; // exclusive
}
if (next != null) {
next.handle(req);
}
}
public static void main(String[] args) {
Handler chain = new PrefixHandler("a:", new PrefixHandler("b:", null));
chain.handle("b:2"); // prints: b: got b:2
chain.handle("a:1"); // prints: a: got a:1
}
}Common Gotchas
Forgetting `next` drops the request
have a terminal handler that errors on unhandled input.
Servlet filters are a pipe
not calling `chain.doFilter` stops the request.