命令模式似乎不必要地复杂(我有什么不明白的?) [英] Command Pattern seems needlessly complex (what am I failing to understand?)

查看:33
本文介绍了命令模式似乎不必要地复杂(我有什么不明白的?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了命令模式,我想我遗漏了一些东西.Command 对象的存在是为了抽象出 Receiver 对象的细节.在我看来,我们可以简单地停在这里,并持有对 Command 对象的引用,以便在适当的时间执行适当的方法.

I've read up on the Command Pattern, and I think I'm missing something. The Command object exists to abstract away the details of the Receiver object. It seems to me that we could simply stop here, and hold references to Command objects to execute the appropriate method at the appropriate time.

那么,为什么需要调用者?这个额外的间接提供什么好处?我们已经将 Receiver 的细节隐藏在 Command 背后,那么 Command 对客户端隐藏的动机是什么?

Why, then, is the Invoker needed? What advantage does this additional indirection provide? We've already hidden the details of the Receiver behind the Command, what's the motivation for the Command to then be hidden from the client as well?

推荐答案

好吧,如果你这样说,它看起来相当复杂,但通常 Receiver 根本不需要是一个对象.它可以不仅仅是一个被执行的函数(作为一个事件).此外,调用者不需要是一个类.它只是触发命令的东西.这也可以是按钮中的事件处理程序.

Well, if you put it that way, it seems quite complex, but often a Receiver doesn't need to be an object at all. It can be little more than just a function that is executed (as an event). Also, the invoker doesn't need to be a class. It is just the thing that triggers the command. This also can be an event handler in a button.

甚至 维基百科 总结了几个使用此模式而无需实际实施的示例为调用者和接收者完成单独的类.一个例子是一个向导对话框,其中 GUI 填充命令对象,完成按钮触发它.所以那个 GUI 类(无论如何你都有)既是客户端又是调用者.

Even Wikipedia sums up a couple of examples where this pattern is used without actually having to implement complete separate classes for invoker and receiver. An example is a wizard dialog, where the GUI populates the command object, and a Finish button triggers it. So that GUI class (that you have anyway) is both the client and the invoker.

这篇关于命令模式似乎不必要地复杂(我有什么不明白的?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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