1. Command mode 1.1 traditional command mode
Application scenario of the command pattern: the sender of the request and the requesting recipient eliminate the coupling relationship
Take the page click button for example
After clicking the button, the command object is used to unlock the coupling between the button and the specific Behavior object.
<body> <button id= ' button1 ' > button 1</button> <button id= ' button2 ' > button 2</button> <button id= ' button3 ' > button 3</button></body><script> var button1=document.getelementbyid (' button1 '); var button2=document.getelementbyid (' button2 '); var button3=document.getelementbyid (' Button3 '); </script>
Defines the SetCommand function, binding behavior.
var setcommand=function(button,command) { Button.onclick=function() { Command.Execute (); }}
Finally, write specific behaviors that complete several functions of the menu bar
var menubar={ refresh:function() { console.log (' refresh '); }}; var submenu={ add:function() { Console.log (' Add '); }, del: function() { console.log (' del '); }};
Encapsulate behavior in the command class
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;};D ElSubMenuCommand.prototype.execute=function{ This. Receiver.del ();}
Finally, the command receiver is passed into the commands object, and the order object is bound to the button
var refreshmenubarcommand=New Refreshmenubarcommand (MenuBar); var addsubmenucommand=New Addsubmenucommand (submenu); var delsubmenucommand=New Delsubmenucommand (submenu); SetCommand (button1, Refreshmenubarcommand); SetCommand (Button2,addsubmenucommand); SetCommand (Button3,delsubmenucommand) ;
1.2 JavaScript this command pattern
var bindclick=function (Button,func) {button.onclick =func;}; var Menubar={refresh: function () {Console.log ( ' refresh ' ); }}; var Submenu={add: () {Console.log ( ' Add ' ); }, Del: function () {Console.log ( ' del ' ); }};bindclick (Button1,menubar.refresh); Bindclick (Button2,submenu.add); Bindclick (Button3,submenu.del);
"JavaScript design patterns and Development practices" command mode for reading notes