Chain of Responsibility
Category
Behavioral pattern
Problem
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain.
Solution
- Create a chain of handler objects, each capable of processing the request
- Each handler decides whether to process the request or pass it to the next handler
- The chain can be dynamically assembled and modified
Structure
- Handler: Interface defining a method for handling requests; holds a reference to the next handler
- ConcreteHandler: Processes requests it can handle; passes others to the next handler
- Client: Creates the chain and sends a request to the first handler
Key Benefits
- Loose coupling — Sender and receiver are decoupled; any handler in the chain can respond
- Open/Closed Principle — New handlers can be added without modifying existing ones
- Flexibility — The chain can be reconfigured at runtime
Trade-offs
- No guarantee of handling — A request might reach the end of the chain unhandled
- Debugging complexity — The request path through the chain can be hard to trace
When to Use
- More than one object may handle a request, and the handler isn’t known explicitly
- You want to submit a request to a set of objects without specifying the receiver
- The set of handlers should be specified dynamically