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

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

问题描述

我只是在阅读责任链模式,我当我更喜欢使用它而不是 decorator 时,很难想象一个场景.

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?

推荐答案

责任链模式与装饰者模式的不同之处在于,你可以在任何时候打破链条.装饰器可以被认为是一次执行,而不与其他装饰器进行任何交互.链中的链接可以被认为是一次执行一个,因为它们每个都依赖于前一个链接.

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.

如果在该示例中使用了装饰器模式,您会收到 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天全站免登陆