Chain of Responsibility Pattern

责任链模式是一种设计模式,用于处理一组相互依赖的类,并确保每个类控制何时及将处理传递给哪个类。此模式通过继承和允许实例加载其前身来控制代码流程,形成一个将处理传递给链中下一个类的类链。它类似于命令模式和组合模式,但更严格地定义了操作顺序。
What Is a Chain of Responsibility Pattern

The Chain of Responsibility pattern performs a lot like it sounds. If you have a group of classes that are all interdependent on each other and each performs a particular piece of processing, this pattern is a very useful tool. It makes sure each member in a chain controls when and to what class it hands its processing to. The pattern controls the code flow by using inheritance and by allowing instances of its predecessors to be loaded one inside the other, forming in effect a chain of classes that hand off to the next class in the chain at the end of its turn.

The Chain of Responsibility pattern has a single main component: the Handler. The handler object encapsulates the entire chain of handler instances inside each other instance. In other words, the first link in the chain contains the next and that link contains each consecutive link. As you move through each link’s process and that process finishes, it automatically checks for the existence of the next consecutive link and calls the process of that next link. This can happen no matter which level of link in the chain you call and will continue down the chain until the chain ends.
UML for Chain of Responsibility pattern

Comparison to Similar Patterns
Depending on whether you wish to provide a set operational cycle or you want to change that cycle on the fly might influence your decision to use the Chain of Responsibility pattern or a Command pattern. The Command pattern holds an order of operations in its command queue, but allows ad-hoc calls to any operation desired via the command object. In contrast, the Chain of Responsibility pattern more rigidly defines the order of operations. Your particular usage depends on which is more suitable to your needs. The Chain of Responsibility also is like the Composite pattern in that parsing through the class chain is like moving through each collection class in the composite. Both patterns move through class methods in a serial fashion.

What We Have Learned
The Chain of Responsibility pattern seems to be quite a good way to link classes that have interdependence on each other in an order of operations. You could implement the pattern in an approval cycle, where people needed to approve specific requests in turn. You could use it to determine an order of operations for executing nearly any kind of code. This order can easily be changed at run time or in different code instances, depending on the need.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值