简体   繁体   English

命令模式的使用

[英]The use of command patterns

I just started reading a book called "Game Programming Patterns". 我刚开始读一本书,叫做“游戏编程模式”。 In the very beginning, a simple pattern called the command pattern was explained, and the example for it was to be able to configure the action that specific keys trigger. 在开始时,解释了一个简单的模式,称为命令模式,并且该示例的示例是能够配置特定键触发的动作。 But, actually, I have a question on that. 但是,实际上,我对此有疑问。 Why would you use Commands to trigger those actions instead of just doing something like: 为什么要使用命令来触发这些操作,而不是仅仅执行以下操作:

Map<Key, Action> map
if(isPressed(key)) map.get(key).trigger()

The result would be the same, and frankly, it seems a bit more effective in my mind. 结果将是相同的,并且坦率地说,在我看来,它似乎更有效。 Could anyone please explain to me why, in that situation, you would use the command pattern instead of my example above? 谁能向我解释为什么在这种情况下,您将使用命令模式而不是上面的示例?

Command Pattern Example: 命令模式示例:

Command* this_specific_key_command;
if(isPressed(key)) this_specific_key_command.trigger()

Where the command class is something like 命令类是这样的

class Command{
    virtual void trigger() = 0;
}

Sorry for the messed up code. 很抱歉弄乱了代码。 I hope it is understandable. 我希望这是可以理解的。

Actually your first implementation is exactly a command pattern. 实际上,您的第一个实现正是命令模式。 The definition of a command pattern is as follows: 命令模式的定义如下:

The Command Pattern encapsulates a request as an object, thereby letting you
parameterize other objects with different requests, queue or log requests, and support
undoable operations.

The first sentence in this definition defines the command pattern. 此定义中的第一句话定义了命令模式。 Both samples you provided are equivalent. 您提供的两个样本都是等效的。 In the first one you call the object Action, while in the second you call it Command. 在第一个中,您将对象称为Action,在第二个中,您将其称为Command。 Both of these are exactly the same. 两者完全相同。 They are the object (the definition refers to) that encapsulates the request. 它们是封装请求的对象(定义所指的对象)。

It doesn't matter if you are storing a pointer or using a map to store these commands. 是存储指针还是使用映射存储这些命令都没有关系。 The important thing is that these object have a method called trigger() that is encapsulating the request(or the action to be done).This is what makes the command pattern. 重要的是这些对象有一个称为trigger()的方法,该方法封装了请求(或要完成的动作)。这就是命令模式的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM