命令模式

解開請(qǐng)求調(diào)用者和接受者之間的耦合關(guān)系。

  • 菜單程序例子
  1. 點(diǎn)擊按鈕,發(fā)送請(qǐng)求,但是不知道接收者是誰,也不知道接收者做怎樣的處理。
<button id="button1">點(diǎn)擊按鈕1</button>
<button id="button2">點(diǎn)擊按鈕2</button>
<button id="button3">點(diǎn)擊按鈕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.按下按鈕會(huì)發(fā)生一些事情是不變的,具體發(fā)生什么事情是可變的。

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對(duì)象中,把command對(duì)象安裝到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中命令模式
    簡(jiǎn)化了上面的操作,沒用引入command對(duì)象和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 );
  • 撤銷和重做
    可以把命令先保存在堆棧。執(zhí)行重做命令時(shí),從堆棧中依次取出命令并執(zhí)行。
  • 宏命令
    一次可以執(zhí)行一批命令。這些都是先用一個(gè)變量將命令先緩存下來,當(dāng)執(zhí)行命令時(shí),遍歷這個(gè)對(duì)象,并依次執(zhí)行命令。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容