相关概念
Chain-of-Responsibility Pattern: 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 until an object handles it.
- 观察者允许接收者动态地订阅或取消接收请求。
- 命令在发送者和请求者之间建立单向连接。
- 中介者清除发送者和请求者之间的直接连接, 强制它们通过一个中介对象进行间接沟通。
- 责任链按照顺序将请求传给一系列的潜在接收者, 直至其中一名接收者处理请求。
实现代码
处理者
具体处理者
测试类
Q & A
What are the advantages of using a chain-of-responsibility design pattern?
- You can have more than one object to handle a request.
- Notice that if a handler cannot handle the whole request, it may forward the responsibility to the next handler in the chain.
- The nodes of the chain can be added or removed dynamically. Also, you can shuffle the order.
- For example, if you notice that the majority of issues are with email processing, then you may place
EmailErrorHandler
as the first handler in the chain to save the average processing time of the application.
- A handler does not need to know how the next handler in the chain will handle the request. It focuses only on its own handling mechanism.
What are the challenges associated with using the chain-ofresponsibility design pattern?
- There is no guarantee that the request will be handled (fully or partially) because you may reach the end of the chain.
- Debugging may become tricky with this kind of design.
It appears that there are similarities between the observer pattern and the chain-of-responsibility pattern. Is this correct?
- In an observer pattern, all registered users get notifications in parallel.
- In a chain-of-responsibility pattern, objects in the chain are notified, one by one, in a sequential manner. This process continues until an object handles the notification fully.