Chain Of Responsibility
08 Mar 2022Intent
Avoid coupling the sender of a request to it's receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Applicability
Use chain of responsibility when:
- more than one object may handle a request, and the handler isn't known a priori. The handler should be asertained automatically.
- you want to issue a request to one of several objects without specifying the receiver explicitly.
- the set of objects that can handle a request should be specified dynamically.
Structure
Participants
- Handler: defines an interface for handling requests, implements the successor link.
- ConcreteHandler: handles requests it is responsible for, can access it's successor.
- Client: initiates the request to a ConcreteHandler object on the chain.
Collaborations
When a client issues a request, the request propogates along the chain until a ConcreteHandler object takes responsibility for handling it.
Consequences
COR has the following benefits:
- Reduced coupling: the pattern frees an object from knowing which other object handles a request.
- Added flexibility in assigning responsibilities to object.
- Receipt isn't guaranteed.
Sample Code
Related Patterns
COR is often applied in conjunction with Composite. There, a component parent can act as it's successor.