不同版本的命令模式

命令模式的意圖是把請求封裝為隊形,從而分離請求的發(fā)起者和請求的接收者的耦合關(guān)系,下面是三種不同版本的命令模式


//對象關(guān)聯(lián)的命令模式
// function createAndConnect(original,propertyObject){
// var clone = Object.create(original);
// if(typeof propertyObject == "object"&&propertyObject!=null){
// for(var key in propertyObject){
// clone[key] = propertyObject[key];
// }
// }
// return clone;
// }
// var TV = { //變化內(nèi)容
// open:function(){
// alert('打開電視機');
// },
// close:function(){
// alert('關(guān)閉電視機');
// }
// }
// var openTvCommand = { //電視命令對象
// execute:function(){
// this.open();
// },
// undo:function(){
// this.close();
// }
// };
// var setCommand = function(receiver,command){
// var obj = createAndConnect(command,receiver); //電視對象關(guān)聯(lián)其命令對象
// document.getElementById('execute').addEventListener('click',function(){
// obj.execute();
// },false);
// document.getElementById('undo').addEventListener('click',function(){
// obj.undo();
// },false);
// }
// setCommand(TV,openTvCommand);

// 面向類的命令模式
// var TV = { //變化內(nèi)容
// open:function(){
// alert('打開電視機');
// },
// close:function(){
// alert('關(guān)閉電視機');
// }
// }
// var openTvCommand = function(receiver){ //初始化命令對象,命令對象里面應(yīng)該有一個接受者
// this.receiver = receiver;
// }
// openTvCommand.prototype.execute = function(){
// this.receiver.open();
// }
// openTvCommand.prototype.undo = function(){
// this.receiver.close();
// }
// var setCommand = function(command){
// document.getElementById('execute').onclick = function(){
// command.execute();
// };
// document.getElementById('undo').onclick = function(){
// command.undo();
// }
// }
// setCommand(new openTvCommand(TV)); //初始化電視命令對象,其receiver為TV對象,當(dāng)命令對象執(zhí)行execute和undo時,由TV對象接收

//閉包版本的命令模式
var TV = { //變化內(nèi)容
open: function () {
alert('打開電視機');
},
close: function () {
alert('關(guān)閉電視機');
}
}
var createCommand = function (receiver) {
var execute = function () {
return receiver.open();
}
var undo = function () {
return receiver.close();
}
return {
execute: execute,
undo: undo
}
}
var setCommand = function (command) {
document.getElementById('execute').onclick = function(){
command.execute();
};
document.getElementById('undo').onclick = function(){
command.undo();
}
}
setCommand(createCommand(TV));

本文參考自《Javascript設(shè)計模式與開發(fā)實踐》

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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