解開請(qǐng)求調(diào)用者和接受者之間的耦合關(guān)系。
- 菜單程序例子
- 點(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( '刪除子菜單' );
};
- 命令接收者傳入到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 );
- 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í)行命令。