One, general overview
1, the author discusses
In our daily life, when we watch TV, we choose our favorite channel through the remote control, at this time we are the role of the client, the button of the remote control is equivalent to the customer request, and the specific object of execution is the command object,
The command pattern encapsulates a request or operation into an object. The command mode allows the system to parameterize the client using different requests, queue requests, or log request logs, which can provide undo and redo functions for the command.
Let's give a concrete example, as follows:
1 functionAdd (x, y) {returnX +y;} ;2 functionSub (x, y) {returnX-y;} ;3 functionMul (x, y) {returnX *y;} ;4 functionDiv (x, y) {returnX/y;} ;5 6 varCommand =function(execute, Undo, value) {7 This. Execute =Execute;8 This. Undo =undo;9 This. Value =value;Ten } One A varAddCommand =function(value) { - return NewCommand (Add, sub, value); - }; the - varsubcommand =function(value) { - return NewCommand (Sub, add, value); - }; + - varMulcommand =function(value) { + return NewCommand (mul, Div, value); A }; at - varDivcommand =function(value) { - return NewCommand (Div, mul, value); - }; - - varCalculator =function () { in varCurrent = 0; - varcommands = []; to + functionAction (command) { - varName = Command.execute.toString (). substr (9, 3); the returnName.charat (0). toUpperCase () + name.slice (1); * } $ Panax Notoginseng return { -Executefunction(command) { theCurrent =Command.Execute (current, command.value); + commands.push (command); ALog.add (Action command + ":" +command.value); the }, + -Undofunction () { $ varCommand =Commands.pop (); $Current =Command.undo (current, command.value); -Log.add ("Undo" + action (Command) + ":" +command.value); - }, the -GetCurrentValue:function () {Wuyi returnCurrent ; the } - } Wu } - About varLog = (function () { $ varLog = ""; - - return { -Addfunction(msg) {log + = msg + ' \ n '; }, AShowfunction() {alert (log); log = ""; } + } the })(); - $ functionrun () { the varCalculator =NewCalculator (); theCalculator.execute (NewAddCommand (100)); theCalculator.execute (Newsubcommand (24)); theCalculator.execute (NewMulcommand (6)); -Calculator.execute (NewDivcommand (2)); in Calculator.undo (); the Calculator.undo (); theLog.add ("\nvalue:" +Calculator.getcurrentvalue ()); About log.show (); the}
This is an example of a calculator that encapsulates each specific operation in the form of an object, and when the calculator receives our request,
To give a specific order, is +,-, or * *. In this way, we pass the request to the calculator and the calculator to execute exactly what commands are required.
So although the result is the same, it is calculated results, but the process is very different. Maximum reduction of coupling.
Second, source case reference
The general idea in the command mode is that it gives us a separate mandate for any execution of commands, such responsibility for different objects rather than authorization.
A simple command object that combines a behavior object to invoke an action. They always include an execution action (such as run () or execute ()). All command objects have the same interface and can be easily exchanged for need.
Third, the introduction of the case
The specific command pattern code is various, because how to encapsulate commands, different systems, have different practices. The following example is to encapsulate a command in a list, any object once added to the list, actually loaded into a closed black box, the object's characteristics disappeared, only when taken out, it is possible to blur the resolution:
A typical command pattern requires an interface with a unified approach, which is "encapsulate commands/requests as objects".
(1), building a program Ape entity class
1 function Programmer () {2 This function () {3 console.log ("Program Ape Write code! ") ; 4 } ; 5 };
(2) to establish an engineer entity class
1 function Engineer () {2 This function () {3 Console.log ("The engineer built the house!") ") ; 4 } ; 5 };
(3) To establish a politician entity class
1 function politician () {2 This function () {3 Console.log ("Politician squirting!") ") ; 4 } ; 5 };
(4), Set up black box class
As a general rule, we can call these three command directly, but using the command mode, we'll wrap them up and throw them into the black box list:
1 functionProducer () {2 varList = [] ;3 return {4Producerequests:function(){5List.push (NewEngineer ());6List.push (NewProgrammer ());7List.push (Newpolitician ());8 returnlist;9 }Ten } One}
These three commands entered the list, has lost its appearance features, and then removed, may not be able to tell who is engineer, who is programmer, see below how the client calls Command mode:
(5), set up the command client class
1 function cmdclient () {2 var cmdlist = producer.producerequests (); 3 for (var in cmdlist) {4 (Cmdlist[p]). Execute (); 5 }6 };
Understand the core principle of the above code, in use, should each have their own method, especially in how to separate the caller and the specific command, there are many implementations, the above code is the use of "from list over again" approach. This is just a demonstration.
A good reason to use the command mode is also because it implements the Undo feature. Each specific command remembers the action it just performed and resumes when needed.
Four, summarize
Commands have the following advantages:
(1) The command mode makes it easy to add new commands to the system.
(2) Allow the party receiving the request to decide whether to veto the request.
(3) It is easier to design a command queue.
(4) The revocation and recovery of the request can be easily achieved.
(5) If required, it is easier to log commands into the logs.
More loosely coupled
The command pattern completely decouples the object that originated the command-the client, and the object that implements the command-that is, the object that initiated the command is completely unaware of who the implementation object is and how it is implemented.
More dynamic control
The command mode encapsulates the request, and it can be parameterized, queued and journaled dynamically, which makes the system more flexible.
It's a natural compound command.
Command objects in command mode can be easily combined into composite commands, which are macro commands, making the system easier to operate and more powerful.
Better extensibility
Since the object that initiated the command is fully decoupled from the specific implementation, it is easy to extend the new command, just implement the new command object, then set the specific implementation object to the Command object when assembling, and then you can use the command object, and the existing implementation does not have to change at all.
Application Scenarios
1) Use the command mode as an alternative to "CallBack" in an object-oriented system. The "CallBack" is about registering a function first, and then calling this function later.
2) You need to specify the request at different times and queue the request. A Command object and the original request issuer can have different lifetimes. In other words, the original request issuer may already be gone, and the command object itself is still active. At this point the recipient of the command can be either local or another address on the network. The command object can be routed to another machine after serialization.
3) The system needs to support undo for the command. The Command object can store the state and wait until the client needs to undo the effect of the command, and the Undo () method can be called to undo the effect of the command. The Command object can also provide the redo () method for the client to re-enforce the command effect when needed.
4) If a system to update all the data in the system to the log, so that when the system crashes, you can read back all the data update commands in the log, re-call the Execute () method one line to execute these commands, to restore the system before the crash of data updates.
hahaha, the end of this article, not to be continued, hope and we have enough communication, common progress (*^__^*) call ... (*^__^*)
Big Xun Jun talk about JS and design mode------Command mode