JS and design pattern ------ Command pattern Command

Source: Internet
Author: User

JS and design pattern ------ Command pattern Command
First, give a specific example, as follows: 1 function add (x, y) {return x + y ;}; 2 function sub (x, y) {return x-y ;}; 3 function mul (x, y) {return x * y;}; 4 function div (x, y) {return x/y ;}; 5 6 var Command = function (execute, undo, value) {7 this.exe cute = execute; 8 this. undo = undo; 9 this. value = value; 10} 11 12 var AddCommand = function (value) {13 return new Command (add, sub, value); 14}; 15 16 var SubComm And = function (value) {17 return new Command (sub, add, value); 18}; 19 20 var MulCommand = function (value) {21 return new Command (mul, div, value); 22}; 23 24 var DivCommand = function (value) {25 return new Command (div, mul, value); 26 }; 27 28 var Calculator = function () {29 var current = 0; 30 var commands = []; 31 32 function action (command) {33 var name = command.exe cute. toString (). substr (9, 3 ); 34 return name. charAt (0 ). toUpperCase () + name. slice (1); 35} 36 37 return {38 execute: function (command) {39 current = command.exe cute (current, command. value); 40 commands. push (command); 41 log. add (action (command) + ":" + command. value); 42}, 43 44 undo: function () {45 var command = commands. pop (); 46 current = command. undo (current, command. value); 47 log. add ("Undo" + action (command) + ":" + command. Value); 48}, 49 50 getCurrentValue: function () {51 return current; 52} 53} 54} 55 56 var log = (function () {57 var log = ""; 58 59 return {60 add: function (msg) {log + = msg + "\ n" ;}, 61 show: function () {alert (log); log = "" ;}62} 63}) (); 64 65 function run () {66 var calculator = new Calculator (); 67 calculator.exe cute (new AddCommand (100); 68 calculator.exe cute (new SubCommand (24); 69 calculator. Execute (new MulCommand (6); 70 calculator.exe cute (new DivCommand (2); 71 calculator. undo (); 72 calculator. undo (); 73 log. add ("\ nValue:" + calculator. getCurrentValue (); 74 log. show (); 75} is an example of a calculator. Each specific operation is encapsulated in the form of an object. After receiving our request, the calculator sends a specific command +, -, or */. In this way, we send the request to the calculator and the calculator to execute the required commands. In this way, although the results are the same, the results are calculated, but the process is completely different. Coupling is minimized. 2. The general idea of the source code case reference in the command mode is that it provides us with a separate responsibility for executing any command and releasing the command. The different objects of this responsibility are not authorized. A behavior object that combines simple command objects to call an action. They always include an execution operation (such as run () or execute ()). All command objects have the same interface and can be easily exchanged. 3. The case introduces various types of specific Command mode code, because there are different practices for how to encapsulate commands and different systems. In the following example, commands are encapsulated in a List. Once any object is added to the List, a closed black box is actually loaded, and the Object Features disappear, it is possible to blur the distinction: a typical Command mode requires an interface with a unified method, which is "encapsulating commands/requests as objects ". (1), create the program ape entity Class 1 function Programmer () {2 this.exe cute = function () {3 console. log ("program ape write code! "); 4}; 5}; (2), set up Engineer entity Class 1 function Engineer () {2 this.exe cute = function () {3 console. log (" Engineer builds a house! "); 4}; 5}; (3), create a Politician entity Class 1 function Politician () {2 this.exe cute = function () {3 console. log ("a politician sprayed! "); 4}; 5}; (4). To create a black box class, we can directly call these three commands, but in the Command mode, we want to encapsulate them and drop them into the black box List: 1 function Producer () {2 var list = []; 3 return {4 produceRequests: function () {5 list. push (new Engineer (); 6 list. push (new Programmer (); 7 list. push (new Politician (); 8 return list; 9} 10} 11} after the three commands enter the List, they have lost their external features and will be retrieved later, you may not be able to tell who is an Engineer and who is a Programmer. Let's see how the following client calls the Command mode: (5), create the Command client Class 1 fu Nction export client () {2 var cmdlist = Producer. produceRequests (); 3 for (var p in cmdlist) {4 ({list?p=cmd.exe cute (); 5} 6}; understand the core principles of the above Code, in use, each user should have their own method, especially on how to separate callers and specific commands, there are many implementation methods, the above Code is to use the "from List once" approach. this is just for demonstration. A good reason for using the Command mode is that it can implement the Undo function. every specific command can remember the action it just executed and restore it as needed. 4. The command has the following advantages: (1) the command mode makes it easy for new commands to be added to the system. (2) The requesting party is allowed to decide whether to reject the request. (3) It is easier to design a command queue. (4) The request can be easily revoked and restored. (5) When necessary, it is easier to log commands. The loose coupling command mode completely decouples the client object that initiates the command from the receiver object of the specific implementation command. That is to say, the object that initiates the command has no idea who the specific implementation object is, I do not know how to implement it. The more dynamic control command mode encapsulates the request and can dynamically parameterize, queue, and log the request to make the system more flexible. Naturally, the command objects in the composite command mode can be easily combined into composite commands, that is, macro commands, making system operations simpler and more powerful. Better scalability because the object initiating the command is completely decoupled from the specific implementation, it is easy to expand the new command. You only need to implement the new command object, and then during assembly, set the specific implementation object to the command object, and then you can use this command object. The existing implementation does not need to be changed at all. Application Scenario 1) Use the command mode as an alternative to "CallBack" in the object-oriented system. "CallBack" refers to registering a function and then calling it later. 2) You must specify the request at different times and queue the request. A command object and the original request sender can have different lifecycles. In other words, the original request sender may no longer exist, and the command object itself is still active. At this time, the command receiver can be local or another address on the network. The command object can be transmitted to another machine after being serialized. 3) The system must support undo commands ). The command object can store the status. When the client needs to revoke the effect of the command, it can call the undo () method to cancel the effect of the command. The command object can also provide the redo () method for the client to re-execute the command when needed. 4) if a system wants to update all the data in the system to the log, so that when the system crashes, it can read all the data update commands in the log and re-call Execute () to restore the data updates made by the system before the crash.

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.