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

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

问题描述

我已经阅读了命令模式,我觉得我错过了一些东西。存在Command对象来抽象出Receiver对象的细节。在我看来,我们可以简单地在这里停下来,并保留对Command对象的引用,以在适当的时候执行适当的方法。



为什么Invoker需要?这个附加间接提供什么优点?我们已经把接收器的细节隐藏在命令之后,命令的动机是什么,然后被隐藏起来呢?

解决方案

嗯,如果你这样说,这看起来很复杂,但是经常一个Receiver不需要是一个对象。它可以只是一个被执行的功能(作为一个事件)。此外,调用者不需要是一个类。只是触发命令的事情。这也可以是按钮中的事件处理程序。



甚至维基百科总结了使用这种模式的几个示例,实际上不需要为调用者和接收器实现完整的独立类。一个示例是向导对话框,其中GUI填充命令对象,并且完成按钮触发它。所以GUI类(你还有)都是客户端和调用者。


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.

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?

解决方案

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.

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天全站免登陆