匿名函数是实现命令模式的好方法吗?
我对这种模式很陌生......
I'm quite new to this pattern...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我对这种模式很陌生......
I'm quite new to this pattern...
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
如果您有 lambda,那么您实际上并不需要一半的“设计”“模式”。
工厂? 这只是一个返回新对象的函数。 游客? 呃! 命令? 匿名函数。 翻译? 接受字符串或其他内容的函数。 战略? 这是一个函数!
这只是 lambda、函数和闭包。
问题是,其中大约 1/3 到 1/2 基本上是在掩盖缺陷在 C++ 中,其他语言中不存在。 尽管我不再是 Perl 的忠实粉丝,但我不得不承认 Perl 社区首先(或者至少是最有趣的)注意到了这一点。 他们指出,许多所谓的模式实际上是 C++ 中函数式编程的实现。
所以,是的,您可以在使用命令模式的地方使用匿名(或以其他方式命名)函数。
If you've got lambdas, you don't really need half of "design" "patterns" altogether.
Factory? That's just a function returning new objects. Visitor? Duh! Command? Anonymous function. Interpreter? Function which takes string or whatever. Strategy? It's a function!
That's just lambdas, functions and closures.
The problem is, about 1/3 to 1/2 of them were basically cover-ups for deficiencies in C++ that don't exist in other languages. Although I'm not a huge Perl fan anymore, I have to admit the Perl community caught on to this first (or at least funniest). They pointed out that many of these so-called patterns were actually an implementation of Functional Programming in C++.
So yes, you can use anonymous (or otherwise named) functions where you would use the Command pattern.
如果您的命令仅支持一种操作,则可以安全地使用匿名函数。
然而,每个命令有多个操作的情况并不少见。 例如,DoCommand/UndoCommand 用于撤消/重做处理。 或者 CanExecuteCommand/ExecuteCommand 启用/禁用命令的 UI 功能。 或者像 GetLocalizedCommandName 这样的东西。 在这些情况下我会使用接口(而不是例如匿名函数的元组)。
If your command supports only one operation, you can safely use an anonymous function.
However, it's not uncommon to have more than one operation for each command. E.g. DoCommand/UndoCommand for undo/redo-handling. Or CanExecuteCommand/ExecuteCommand to enabled/disable UI features for the command. Or something like GetLocalizedCommandName. I would use an interface in these cases (instead of e.g. a tuple of anonymous functions).
我会说不,因为函数不能真正封装命令的细节,如果它是匿名的,调用者和被调用者如何理解它代表的内容?
(如果有人想学究气一点,GoF 对 Copmmand 模式的描述专门描述了使用对象来进行封装,排除了基于函数的实现,尽管这可能是吹毛求疵的)。
I would say no, on the basis that a function cannot really encapsulate the details of a command, and if it as anonymous how can both the caller and callee understand what it represents?
(If one wanted to be pedantic, the GoF description of the Copmmand pattern specifically describes the use of an object to do the encpsulation, preclusing a function based implenetation, though that would be nit-picking).