Goal: The primary objective is to decouple the sender of an event or request from potential receivers.
The receiving objects form a chain. Basically, they form a linked list so that each object can reference the next one. The request travels through this chain. Each receiving object can decide whether it processes the request.
If an object doesn’t handle the request, it forwards it to the next handler in the chain. The request travels until one of the responder objects handles it.
If none of the objects processes the request, it will reach the end of the chain and nothing happens.
Sometimes you may need to forward the request even if it was processed by one of the responders. What happens if none of the responders takes ownership of the request? The request keeps traveling through the chain until it reaches the end of the chain.
The chain of responsibility organizes potential request processors in a sequence and decouples responders from callers. The request travels until one of the responders processes it or until itreaches the end of the chain.
Example flow: The client fires the request, which reaches the first responder object in the chain. This object doesn’t handle the request, so it forwards it to the next responder. The second responder doesn’t handle the request either. The request travels further through the chain of responders. Now the third responder object decides to handle the request. The request propagation stops here. The next responders are not notified about the request.
The chain-of-responsibility design pattern stands at the core of the responder chain in iOS and macOS.
- This pattern organizes request processors in a chain.
- Responders may or may not process the request.
- Each responder may handle the request, forward it to the next responder, or forward the request after it processes it.
- The request gets propagated through the chain until it reaches the last responder in the chain.
It is a widely-used pattern that can solve various problems that require passing the request betweenobjects organized in a sequence.
Disadvantage: exposing details of any responder from the chain to other objects in the chain or to the caller.