Chain of Responsibility Pattern
What you'll learn: You'll discover how to decouple request senders from receivers by passing requests through a chain of handlers, where each handler decides whether to process or forward the request.
The Core Idea
The Chain of Responsibility pattern lets you pass a request along a chain of potential handlers until one of them handles it—or the request reaches the end unhandled. Each handler contains a reference to the next handler in the chain and decides: "Is this my job?" If yes, process it. If no, pass it along.
Think of it like customer support: your email first goes to a chatbot, then tier-1 support, then tier-2 specialists, and finally a senior engineer. Each level tries to solve your problem; if they can't, they escalate it to the next level.
Why Use This Pattern?
- Decoupling: The sender doesn't need to know which handler will process the request
- Flexibility: You can add, remove, or reorder handlers without changing client code
- Single Responsibility: Each handler focuses on one type of request
Key Characteristics
Each handler typically:
- Checks if it can handle the request
- Either processes it OR forwards it to the next handler
- May modify or log the request before forwarding
Common Use Cases
- Authorization systems (checking permissions at multiple levels)
- Event bubbling in UI frameworks
- Logging frameworks (routing messages by severity)
- Validation pipelines (multiple validation checks in sequence)
- Request filtering and middleware in web servers
Unlike the Command pattern (which encapsulates operations), Chain of Responsibility focuses on dynamically routing requests through a series of handlers.
Key Takeaway: Chain of Responsibility decouples request senders from receivers by passing requests through a handler chain where each handler independently decides to process or forward the request, enabling flexible and extensible request processing pipelines.