Chain of Responsibility
Link handlers in a row and pass each request down the row until one takes it, so the sender never has to know which one that is.
Overview
The problem: the sender has to pick the receiver
An employee files an expense. Small amounts need a team lead's approval, larger ones a manager, the largest a director. The first version of the code puts that knowledge in the place that files the expense: an if on the amount that calls the right approver. Every new rule (a second currency, a travel category, a holiday freeze) is another branch in the same method, and every caller that submits expenses must carry the same branches.
Write the rules down and the problem is plain. A team lead approves amounts up to 1,000, a manager up to 10,000 and a director up to 100,000; above that nobody may approve, and the expense is refused. In the first version all four rules live in the same place, the submit method.
The sender knows every receiver and every rule. The Chain of Responsibility pattern moves each rule into the receiver it belongs to, and lines the receivers up.
Interview questions
- Show the smell Chain of Responsibility fixes, and the fix.
- What happens when no handler takes the request?
- How does a middleware pipeline pass the response back?
- Order matters. How do you build the chain so it is easy to get right?
- When is Chain of Responsibility the wrong choice?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio