Chain of Responsibility
Passes a request along a chain of handlers, where each handler decides to process it or pass it to the next handler in the chain.
errorWhat Problem Does the Chain of Responsibility Pattern Solve?
When a request could be handled by multiple objects, hardcoding the handler creates tight coupling. Adding new handlers requires modifying existing code, violating the Open/Closed Principle. The sender shouldn’t need to know which object will ultimately handle the request.
check_circleHow the Chain of Responsibility Pattern Works
Create a chain of handler objects, each with a reference to the next handler. When a request arrives, the first handler either processes it or forwards it. This decouples senders from receivers and allows dynamic chain composition at runtime.
Chain of Responsibility Pattern Architecture
Rendering diagram...
Implementation by Language
Chain of Responsibility Pattern in the Real World
“Like a customer support escalation: your call starts with a front-line agent. If they can’t resolve it, they transfer you to a specialist. If the specialist can’t help, it goes to a manager. Each level either handles it or passes it up the chain.”
Frequently Asked Questions
helpWhat is the difference between Chain of Responsibility and middleware?
Middleware (as in Express.js or ASP.NET) is an implementation of Chain of Responsibility. Each middleware function decides whether to handle the request, modify it, or pass it to the next handler via next(). The pattern is the same — the term 'middleware' is the web framework convention.
helpShould every handler in the chain have a chance to process the request?
There are two variants: 'pure' chains where exactly one handler processes the request and stops, and 'pipeline' chains where every handler processes and passes along. Express middleware uses the pipeline variant. Choose based on whether handlers are mutually exclusive or cumulative.