观察者和命令设计模式,为什么菜单常用命令模式?
问题在于,为什么菜单通常使用命令设计模式而不是观察者模式来实现?
All is in the question, why menus are commonly implemented with the Command Design Pattern and not with the Observer pattern ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两个方面,“调度”,从菜单中选择一个选项或单击一个按钮并运行一些代码。然后是实际运行的代码。
我不知道您指的是哪个 UI 框架,但我希望在这两种情况下都使用观察者模式和命令模式。我想知道发生的情况是否是菜单案例和按钮案例只是由您的框架以使不同方面可见的方式实现的。
因此,对于菜单,您提供不同的命令对象,您实际上永远不会看到导致调用命令的内部调度。我的猜测是在幕后一定会发生一些事件处理,因此观察者模式很可能正在使用,只是您看不到它。
在按钮的情况下,调用的代码可以被视为命令对象,但我们更明确地将其连接到事件,因此我们首先看到观察者模式。
There are two aspects, the "dispatching", an option is selected from a menu or a button is clicked and some code is run. Then there's the actual code that's run.
I don't know which UI framework you are referring to but I'd expect to see both Observer and Command patters used in both cases. I wonder if what's happening is that the Menu case and the Button case are just implemented by your framework in ways that make different aspects visible.
So for menus, you provide different command objects, you never actually see the internal dispatching that causes your command to be invoked. My guess is under the covers some Event handling must be happening, so the Observer pattern might well be in use, it's just you don't see it.
In the button case the code that's invoked can be thought of as a command object but we more explicitly wire it to an event so we first see the Observer pattern.
我可以看到一个使用观察者模式与菜单项或按钮的用例。假设有星座计算器。用户有一个按钮来开始星座生成。用户点击按钮并向服务器发出命令进行计算。稍后,同一按钮可以观察服务器状态,反之亦然,以进行状态更新或显示打印以及来自该按钮的火打印命令。
所以观察者:需要调度事件。
命令:执行的动作。
I can see one use case for using observer pattern with menu Item or button. Assume there is Horoscope calculator. User has a button to start horoscope generation. User will click the button and command issued to server for calculation. Later same button can observe server status or vice versa for status updates or to display print and the fire print command from the button.
So Observer : Events needs to dispatched.
Command: an action performed.