(Use the Chain of Responsibility Pattern when you want to give more than one object a chance to handle a request)
- When you want to decouple a request’s sender and receiver
- Multiple objects, determined at runtime, are candidates to handle a request
- When you don’t want to specify handlers explicitly in your code
- When you want to issue a request to one of several objects without specifying the receiver explicitly.
- Commonly used in Windows systems to handle events like mouse clicks and keyboard events.
- Decouples the sender of the request and its receivers.
- Simplifies your object as it doesn’t have to know about the chain structure and keep direct references to its members.
- Allows you to add or remove responsibilities dynamically by changing the members or order of the chain.
- Mostly, it can get broken easily:
- if a processor fails to call the next processor, the command gets dropped
- if a processor calls the wrong processor, it can lead to a cycle
- It can create deep stack traces, which can affect performance
- It can lead to duplicate code across processors, increasing maintenance
- Execution of the request isn’t guaranteed; it may fall off the end of the chain if no object handles it (this can be an advantage or a disadvantage),
- Can be hard to observe the runtime characteristics and debug.
Note: there is not much discussion about the disadvantage of COR. Whenever we can use it, use it.