Design mode (5): Command mode

Source: Internet
Author: User

Command mode: Also known as action mode or transaction mode. It belongs to the behavior pattern of the object.
The command pattern encapsulates a request or action into an object, and these commands can be:
Repeat multiple times
Cancel
Cancel and redo again

The essence of the command pattern is to encapsulate the command, separating the responsibility for issuing the command from the responsibility of executing the command (decoupling). The command pattern makes the request itself an object that can be stored and passed in the same way as other objects.

The command pattern involves five characters, namely:
Client role: Create a specific command (Concretecommand) object and set the recipient of the command.
Command role: Defines an abstract interface to all command classes, defining a unified execute () interface method.
Specific command (Concretecommand) role: Defines a weak coupling between a receiver and behavior, implements the command interface, and implements the Execute () method, which is responsible for invoking the corresponding operation of the receiver.
Requestor (Invoker) role: Responsible for invoking object execution requests issued by the Client.
Receiver role: Responsible for specific implementation and execution of a request. Any class can be a recipient, and the method of implementing and executing the request is the action method.

This is only a general division, the implementation does not necessarily have these, the design pattern is just the way of thinking construction, there is no one by one corresponding template drop.

   

Look at the code:

usingSystem;usingSystem.collections.generic;namespace commandpattern{ Public InterfaceICommand {voidExecute (); }/ * The Invoker class * /     Public classSwitch {PrivateList<icommand> _commands =NewList<icommand> (); Public void Storeandexecute(ICommand command) {_commands.            ADD (command); Command.        Execute (); }    }/ * The Receiver class * /     Public classLight { Public void TurnOn() {Console.WriteLine ("The Light was on"); } Public void Turnoff() {Console.WriteLine ("The Light is Off"); }    }/* The Command for turning on the light-concretecommand #1 * /     Public classFlipupcommand:icommand {PrivateLight _light; Public Flipupcommand(light)        {_light = light; } Public void Execute() {_light.        TurnOn (); }    }/ * The Command for turning off the light-concretecommand #2 * /     Public classFlipdowncommand:icommand {PrivateLight _light; Public Flipdowncommand(light)        {_light = light; } Public void Execute() {_light.        Turnoff (); }    }/ * The test class or Client * /    Internal classprogram { Public Static void Main(string[] args) {Light lamp =NewLight (); ICommand switchup =NewFlipupcommand (lamp); ICommand Switchdown =NewFlipdowncommand (lamp); Switch s =NewSwitch ();stringarg = args. Length >0? args[0]. ToUpper ():NULL;if(arg = ="on") {S.storeandexecute (switchup); }Else if(arg = ="OFF") {S.storeandexecute (Switchdown); }Else{Console.WriteLine ("Argument \" on\ "or \" off\ "is required."); }        }    }}

"Note": In some simple business scenarios, the implementation code can be written directly in the Execute method of the Concretecommand class, eliminating the receiver class to simplify the code. As in this scenario, the Receiver class is omitted from creation.

Consider a practical example:
In the shooting game, the user can customize the shortcut keys, according to the use of the habit to set the shortcut keys, such as "W" key can be set to "fire" shortcut keys, can also be set as "forward" shortcut keys, you can use the command mode to achieve shortcut key settings, the class Figure 5 shows:

   

In the diagram, ShortcutKey acts as the caller of the request, determining which key the user presses in its press () method, and then invoking the Execute () method of the Command object, which in the Execute () method of the specific command object will invoke the recipient such as Shothandler, The action () method of the Goaheadhandler to perform the specific action. When implemented, you can store the specific command class class name and key code (KEYCODE) of the keyboard key in the configuration file, as shown in the configuration file format:

……  <FunctionMapping keycode="87" commandClass="ShotCommand"/>  <FunctionMapping keycode="38" commandClass="GoAheadCommand"/>  ……  

If you need to replace the shortcut keys, just modify the key code and the specific command class mapping relationship, if you need to add a new feature in the upgrade version of the game, just add a new specific command class, you can modify the configuration file to set the corresponding keys, the original class library code without any modification, well conform to the open and close principle.

Applicability: In a software system, a tightly coupled relationship is usually present between the behavior requester and the behavior's implementation. But in some cases, such as the record of behavior to undo redo transactions, such as processing, this can not resist the change of tight coupling is inappropriate. In this case, the command pattern is used to decouple the behavior requester from the behavior implementation.

A typical application scenario is the processing of command queues, which reduces the coupling of behavior requesters and action performers, increases flexibility, and reduces code redundancy.

In addition, there are two implementations of undo transactions:
1) The current state is stored before the Execute () method is executed, and when the Undo () method is called, the current state is converted to the previously stored state (simple, complete information is saved, space is wasted, unnecessary).
2) Save only information that changes between States, and only change these stored information when execute () or undo () is called

Reference:
Https://zh.wikipedia.org/wiki/%E5%91%BD%E4%BB%A4%E6%A8%A1%E5%BC%8F
http://www.ibm.com/developerworks/cn/java/design/
Http://treelib.com/book-detail-id-59-aid-3471.html

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Design mode (5): Command mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.