为什么我会使用装饰品的责任链? [英] Why would I ever use a Chain of Responsibility over a Decorator?

查看:178
本文介绍了为什么我会使用装饰品的责任链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读责任链模式,我是在我喜欢使用装饰器的情况下,无法想象一个场景。

I'm just reading up on the Chain of Responsibility pattern and I'm having trouble imagining a scenario when I would prefer its use over that of decorator.

你觉得怎么样? CoR有利基吗?

What do you think? Does CoR have a niche use?

推荐答案

事实上,您可以在任何时候打破链条,区分链来自Decorator模式的责任模式。装饰器可以被认为是一次执行,而与其他装饰器无任何交互。链接中的链接可以被认为是一次执行一个,因为它们各自依赖于以前的链接。

The fact that you can break the chain at any point differentiates the Chain of Responsibility pattern from the Decorator pattern. Decorators can be thought of as executing all at once without any interaction with the other decorators. Links in a chain can be thought of as executing one at a time, because they each depend on the previous link.

当您使用责任链模式时可以将您的程序概念化为由链接组成的链接,每个链接可以处理请求或将其传递给链。

当我习惯于使用Win32 API,我有时需要使用它提供的钩子功能。挂起Windows消息大致遵循责任链模式。当你挂接一个消息,如WM_MOUSEMOVE,你的回调函数将被调用。将回调函数视为链中的最后一个链接。链中的每个链接都可以决定是否丢弃WM_MOUSEMOVE消息或将其传递给下一个链接。

When I used to work with the Win32 API, I would sometimes need to use the hooking functionality it provides. Hooking a Windows message roughly follows the Chain of Responsibility pattern. When you hooked a message such as WM_MOUSEMOVE, your callback function would be called. Think of the callback function as the last link in the chain. Each link in the chain can decide whether to throw away the WM_MOUSEMOVE message or pass it up the chain to the next link.

如果在该示例中使用了Decorator模式您将收到WM_MOUSEMOVE消息的通知,但您将无力阻止其他钩子处理。

If the Decorator pattern had been used in that example, you would have been notified of the WM_MOUSEMOVE message, but you would be powerless to prevent other hooks from handling it as well.

使用链命令模式的另一个位置是在游戏引擎。再次,您可以挂起引擎功能,事件和其他事情。在游戏引擎的情况下,您不想简单地添加功能。您要添加功能,并阻止游戏引擎执行其默认操作。

Another place the Chain of Command pattern is used is in game engines. Again, you can hook engine functions, events, and other things. In the case of a game engine, you don't want to simply add functionality. You want to add functionality and prevent the game engine from performing its default action.

这篇关于为什么我会使用装饰品的责任链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆