System Design ( Day - 58 )

Chain of Responsibility Pattern
Definition
Allow an object to pass a request along a chain of potential handlers, each handler in the chain decided either to process the request or pass it to the next handler.
🏧 Real-World Example: ATM Cash Dispenser
1. Handler Interface
<<abstract>>
Handler
- next: Handler
+ setNext(handler): void
+ dispense(amount): void
2. Concrete Handlers
ThousandHandler dispenses ₹1,000 notes and forwards the remaining amount.
FiveHundredHandler dispenses ₹500 notes, then forwards.
HundredHandler dispenses ₹100 notes, then forwards.
Each handler checks if the requested amount is ≥ its denomination. If yes, it calculates how many notes, dispenses them, subtracts from the amount, then calls next.dispense(remaining)
.
3. Client Setup
Handler h1 = new ThousandHandler();
Handler h2 = new FiveHundredHandler();
Handler h3 = new HundredHandler();
h1.setNext(h2);
h2.setNext(h3);
// Client just calls:
h1.dispense(3_600);
// Output:
// 3 × ₹1000 notes
// 1 × ₹500 note
// 1 × ₹100 note
The Client doesn’t need to know which handler does the work or how many handlers exist—it just starts the chain.
📐 Standard UML Blueprint
🌟 Why Use Chain of Responsibility?
Extensibility: Add new handlers without changing client code.
Separation of Concerns: Each handler focuses on one type of request.
Dynamic Behavior: Reorder or skip handlers at runtime by changing the chain.
Real-World Example
- Logger
Subscribe to my newsletter
Read articles from Manoj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
