1.命令模式
1.1 传统的命令模式
命令模式的应用场景:请求的发送者和请求接收者消除彼此耦合关系
以页面点击按钮为例
点击按钮后,借助命令对象,解开按钮和负责具体行为对象之间的耦合
<body> <button id='button1'>按钮1</button> <button id='button2'>按钮2</button> <button id='button3'>按钮3</button> </body> <script> var button1=document.getElementById('button1'); var button2=document.getElementById('button2'); var button3=document.getElementById('button3'); </script>
定义setCommand函数,绑定行为。
var setCommand=function(button,command){ button.onclick=function(){ command.execute(); } }
最后编写具体的行为,这些行为完成菜单栏的几项功能
var MenuBar={ refresh:function(){ console.log('refresh'); } }; var SubMenu={ add:function(){ console.log('add'); }, del:function(){ console.log('del'); } };
把行为封装在命令类中
var RefreshMenuBarCommand=function(receiver){ this.receiver=receiver; }; RefreshMenuBarCommand.prototype.execute=function(){ this.receiver.refresh(); }; var AddSubMenuCommand=function(receiver){ this.receiver=receiver; }; AddSubMenuCommand.prototype.execute=function(){ this.receiver.add(); }; var DelSubMenuCommand=function(receiver){ this.receiver=receiver; }; DelSubMenuCommand.prototype.execute=function{ this.receiver.del(); }
最后将命令接收者传入到command对象中,并且将command对象绑定到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这的命令模式
var bindClick=function(button,func){ button.onclick=func; }; var MenuBar={ refresh:function(){ console.log('refresh'); } }; var SubMenu={ add:function(){ console.log('add'); }, del:function(){ console.log('del'); } }; bindClick(button1,MenuBar.refresh); bindClick(button2,SubMenu.add); bindClick(button3,SubMenu.del);