Chain of Responsibility
Pass a request along a linked list of handlers until one deals with it, so the sender does not need to know which one.
The problem it solves
An expense claim arrives. A team lead can approve up to 1,000. A manager up to 10,000. A director up to 100,000. Some users are blocked and must be rejected first. A single method grows into this:
if (blocked.contains(user)) { ... }
else if (amount <= 1000) { ... }
else if (amount <= 10000) { ... }
else if (amount <= 100000) { ... }Every new rule edits the same method, and the order of the rules is buried in the order of the lines.
Chain of Responsibility turns each rule into a handler object with a link to the next one. A request enters at the head. Each handler either deals with it (and the chain stops) or passes it on.
- The sender knows only the head of the chain.
- Handlers do not know the full list, only their
next. - The chain can be rearranged without editing any handler.
You already use this: web middleware (code that runs on each HTTP request before your handler: authentication, logging, rate limits), servlet filters, and log levels all work this way.