命令模式

2018-07-02  本文已影响0人  bby365

解开请求调用者和接受者之间的耦合关系。

  1. 点击按钮,发送请求,但是不知道接收者是谁,也不知道接收者做怎样的处理。
<button id="button1">点击按钮1</button>
<button id="button2">点击按钮2</button>
<button id="button3">点击按钮3</button>
// js
var button1 = document.getElementById( 'button1' ),
var button2 = document.getElementById( 'button2' ),
var button3 = document.getElementById( 'button3' );

var setCommand = function( button, command ){
    button.onclick = function(){
        command.execute();
    }
};

2.按下按钮会发生一些事情是不变的,具体发生什么事情是可变的。

var MenuBar = {
    refresh: function(){
        console.log( '刷新菜单目录' );
    }
};
var SubMenu = {
    add: function(){
        console.log( '增加子菜单' );
    },
    del: function(){
        console.log( '删除子菜单' );
    }
};
// 把 行为封装到命令类中
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(){
    console.log( '删除子菜单' );
};
  1. 命令接收者传入到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. js中命令模式
    简化了上面的操作,没用引入command对象和receiver。
var bindClick = function( button, func ){
    button.onclick = func;
};
var MenuBar = {
    refresh: function(){
        console.log( '刷新菜单界面' );
    }
};
var SubMenu = {
    add: function(){
        console.log( '增加子菜单' );
    },
    del: function(){
        console.log( '删除子菜单' );
    }
};
bindClick( button1, MenuBar.refresh );

bindClick( button2, SubMenu.add );
bindClick( button3, SubMenu.del );
上一篇下一篇

猜你喜欢

热点阅读