代码之家  ›  专栏  ›  技术社区  ›  Iain

匿名函数是实现命令模式的好方法吗?

  •  1
  • Iain  · 技术社区  · 16 年前

    我对这种模式很陌生…

    3 回复  |  直到 16 年前
        1
  •  5
  •   alamar    16 年前

    如果你有lambda,你就不需要“设计”模式的一半。

    工厂?这只是一个返回新对象的函数。访客?噢!命令?匿名函数。翻译?接受字符串或其他内容的函数。战略?这是一个功能!

    这只是lambda、函数和闭包。

    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++.

    因此,可以在使用命令模式的地方使用匿名(或其他命名)函数。

        2
  •  2
  •   Niki    16 年前

    如果命令只支持一个操作,则可以安全地使用匿名函数。

    但是,每个命令都有多个操作并不少见。例如,用于撤消/重做处理的docommand/undocommand。或canexecuteCommand/executeCommand启用/禁用命令的UI功能。或者像getLocalizedCommandName之类的。在这些情况下,我将使用接口(而不是匿名函数的元组)。

        3
  •  0
  •   pauljwilliams    16 年前

    我会说“不”,因为函数不能真正封装命令的细节,如果它是匿名的,那么调用方和被调用方如何理解它所代表的内容?

    (如果你想学点书呆子的话,gof对copmmand模式的描述专门描述了使用一个对象进行封装,排除了基于函数的实现,尽管这很难说)。

    推荐文章