JavaScript Design patterns and development Practices---reading notes (9) Command mode

Source: Internet
Author: User

Purpose of the command mode:

Command mode is one of the simplest and most elegant modes, and command in command mode refers to an instruction that performs certain things.

The most common scenario for command patterns is that you sometimes need to send requests to certain objects, but you don't know who the recipient of the request is or what the requested action is. In this case, it is desirable to design the program in a loosely coupled way, so that the request sender and the requesting receiver can eliminate the coupling relationship between them.

Example of a command pattern-menu program:

<! DOCTYPE html>varbutton1 = document.getElementById (' button1 ')); varButton2 = document.getElementById (' button2 ')); varButton3 = document.getElementById (' Button3 ')); varSetCommand =function(Button,command) {Button.onclick=function() {Command.Execute ();    }    }; varMenuBar ={refresh:function() {Console.log (' Refresh Menu directory '); }, add:function() {Console.log (' Add Menu directory '); }, Del:function() {Console.log (' Delete sub-menu ');    }    }; varRefreshmenubarcommand =function(receiver) { This. Receiver =receiver;    }; RefreshMenuBarCommand.prototype.execute=function(){         This. Receiver.refresh ();    }; varAddsubmenucommand =function(receiver) { This. Receiver =receiver;    }; AddSubMenuCommand.prototype.execute=function(){         This. Receiver.add ();    }; varDelsubmenucommand =function(receiver) { This. Receiver =receiver;    }; DelSubMenuCommand.prototype.execute=function() {Console.log (' Delete sub-menu ');    }; varRefreshmenubarcommand =NewRefreshmenubarcommand (MenuBar); varAddsubmenucommand =NewAddsubmenucommand (submenu); varDelsubmenucommand =NewDelsubmenucommand (submenu);    SetCommand (Button1,refreshmenubarcommand);    SetCommand (Button2,addsubmenucommand); SetCommand (Button3,delsubmenucommand);</script>

The above code simulates the implementation of the command pattern of the traditional object-oriented language.

The origin of the command pattern is actually an object-oriented alternative to the callback function.

varSetCommand =function(button,func) {Button.onclick=function() {func ();    }    }; varMenuBar ={refresh:function() {Console.log (' Refresh Menu directory '); }    };//the command pattern implemented with closures is shown in the following code:    varRefreshmenubarcommand =function(receiver) {return function() {Receiver.refresh ();        }    }; varRefreshmenubarcommand =NewRefreshmenubarcommand (MenuBar); SetCommand (Button1,refreshmenubarcommand);
//change the execution function to invoke the Execute method    varRefreshmenubarcommand =function(receiver) {return{execute:function() {Receiver.refresh ();    }        }    }; varSetCommand =function(Button,command) {Button.onclick=function() {Command.Execute ();    }    }; varRefreshmenubarcommand =NewRefreshmenubarcommand (MenuBar); SetCommand (Button1,refreshmenubarcommand);

Undo command:

The implementation of the undo operation is generally to add a method named Unexecute or undo to the Command object, and perform the exectue reverse operation in the method.

Undo and Redo:

Many times, we need to undo a series of commands. However, in some cases, the undo operation cannot be successfully used to bring the object back to the state before execute.

In canvas drawing, erasing a line is relatively difficult to implement. The best way to do this is to clear the canvas first and then re-execute all the commands you just executed, which can also be done with a history list stack. Logging command logs and then repeating them is a good way to reverse an irreversible command.

<! DOCTYPE html>varRyu ={attack:function() {Console.log (Attack); }, Defense:function() {Console.log (Defense); }, Jump:function() {Console.log (Jump); }, Crouch:function() {Console.log (' Squat down ');    }    }; varMakecommand =function(receiver,state) {return function() {receiver[state] ();    }    }; varcommands = {        "119": "Jump",//W"Crouch"://S"Defense": "The",//A"": "Attack"//D    }; varCommandstack = [];//Save the stack of commandsDocument.onkeypress =function(EV) {varKeyCode =ev.keycode, Command=Makecommand (Ryu,commands[keycode]); if(command) {command (); //Execute CommandCommandstack.push (command);//Save the command you just executed into the stack        }    }; document.getElementById (' Replay '). onclick =function(){//Click to play Video        varcommand;  while(Command = Commandstack.shift ()) {//take the command out of the stack and execute it sequentially.command (); }    };</script>

Command queue

Macro command:

A macro command is a collection of commands that can execute a batch of commands at a time by executing a macro command.

    varClosedoorcommand ={execute:function() {Console.log (Closed);    }    }; varOpenpccommand ={execute:function() {Console.log (' Turn on the computer ');    }    }; varOpenqqcommand ={execute:function() {Console.log (' Login QQ ');    }    }; varMacrocommand =function(){        return{commandslist:[], add:function(){                 for(varI=0,command;command = This. commandslist[i++];                ) {Command.Execute ();    }            }        }    }; varMacrocommand =Macrocommand ();    Macrocommand.add (Closedoorcommand);    Macrocommand.add (Openpccommand);    Macrocommand.add (Openqqcommand); Macrocommand.execute ();

The macro command is the product of the command pattern and the combined pattern.

Smart Commands with fool commands

An invisible pattern in the JavaScript language of the command pattern.

JavaScript Design patterns and development Practices---reading notes (9) Command mode

Related Article

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.