Chain of Responsibility
Pass a request along a chain of handlers; each one either handles it or hands it to the next, so the sender doesn't need to know who deals with it.
Description
Handlers are linked in a line. Each one looks at the request and decides: handle it and stop, or pass it on to the next handler. The sender only knows the first link.
Expense approval is the classic case: a team lead approves small amounts, a director bigger ones, the CFO the largest. HTTP middleware, event bubbling in the DOM and logging levels are the same idea. Adding a step or reordering the chain doesn't touch the sender or the other handlers.
Class diagram
Chain of Responsibility pattern class diagram
- Class ExpenseForm with + submit(expense).
- Abstract class Approver with + setNext(a): Approver, + handle(expense): string, # canApprove(expense).
- Class TeamLead with # canApprove(): ≤ 500.
- Class Director with # canApprove(): ≤ 5 000.
- Class Cfo with # canApprove(): ≤ 50 000.
- ExpenseForm sends to first Approver.
- TeamLead extends Approver.
- Director extends Approver.
- Cfo extends Approver.
Sequence diagram
Chain of Responsibility pattern sequence diagram
- ExpenseForm → TeamLead: handle(42 000, servers).
- TeamLead → Director: handle(…): too big, pass on.
- Director → Cfo: handle(…): too big, pass on.
- Cfo → Cfo: canApprove() → yes.
- Director receives ""CFO approved"" back from Cfo.
- TeamLead receives ""CFO approved"" back from Director.
- ExpenseForm receives ""CFO approved"" back from TeamLead.
TypeScript example
An expense approval chain: team lead, director, CFO. Each approver handles what it can and passes the rest on; the last link rejects anything nobody can approve.
// Chain of Responsibility: an expense goes up the approval chain
// until someone with enough authority handles it.
interface Expense {
who: string;
amount: number;
purpose: string;
}
abstract class Approver {
private next?: Approver;
setNext(next: Approver): Approver {
this.next = next;
return next; // allows a.setNext(b).setNext(c)
}
handle(expense: Expense): string {
if (this.canApprove(expense)) return `${this.title} approved ${expense.amount} for ${expense.purpose}`;
if (this.next) return this.next.handle(expense);
return `nobody can approve ${expense.amount}: rejected`;
}
protected abstract readonly title: string;
protected abstract canApprove(expense: Expense): boolean;
}
class TeamLead extends Approver {
protected readonly title = "Team lead";
protected canApprove(e: Expense): boolean {
return e.amount <= 500;
}
}
class Director extends Approver {
protected readonly title = "Director";
protected canApprove(e: Expense): boolean {
return e.amount <= 5_000;
}
}
class Cfo extends Approver {
protected readonly title = "CFO";
protected canApprove(e: Expense): boolean {
return e.amount <= 50_000 && e.purpose !== "yacht";
}
}
export function demo(): string[] {
const chain = new TeamLead();
chain.setNext(new Director()).setNext(new Cfo());
const expenses: Expense[] = [
{ who: "Sam", amount: 120, purpose: "books" },
{ who: "Kim", amount: 3_200, purpose: "conference" },
{ who: "Alex", amount: 42_000, purpose: "servers" },
{ who: "Robin", amount: 90_000, purpose: "yacht" },
];
return expenses.map((e) => chain.handle(e));
}When to use it
Use it when
- Several objects might handle a request, and which one should is decided at runtime.
- You want to add, remove or reorder processing steps without changing the code that sends requests.
- A request should go through a pipeline where any step may stop it: authentication, validation, rate limiting.
Avoid it when
- Exactly one known object always handles the request. Call it directly.
- Every request must reach a handler, and silently falling off the end would be a bug. Make the final fallback explicit, or use a lookup.
- The order of handlers is hard to see or configure. A table of rules may be clearer than a chain of objects.
Pitfalls
- Requests that fall off the end of the chain unhandled. Always end with an explicit fallback.
- Chains assembled in many places, so the actual order is hard to know. Build each chain in one place.
- Long chains add latency and make stack traces deep. Keep them short.
- Handlers that modify the request and pass it on create hidden coupling between links.
Alternatives
Decorator
Choose it when every layer always forwards the call and adds behaviour; nobody stops it.
Command
Choose it when you want to package requests as objects to queue, log or undo, rather than route them.
Mediator
Choose it when one central object should decide who handles what.
Rules table
Choose it when the routing is pure data, such as amount ranges to approvers: a sorted list and find is enough.