命令模式的意圖是把請求封裝為隊(duì)形,從而分離請求的發(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('打開電視機(jī)');
// },
// close:function(){
// alert('關(guān)閉電視機(jī)');
// }
// }
// 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('打開電視機(jī)');
// },
// close:function(){
// alert('關(guān)閉電視機(jī)');
// }
// }
// var openTvCommand = function(receiver){ //初始化命令對象,命令對象里面應(yīng)該有一個(gè)接受者
// 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時(shí),由TV對象接收
//閉包版本的命令模式
var TV = { //變化內(nèi)容
open: function () {
alert('打開電視機(jī)');
},
close: function () {
alert('關(guān)閉電視機(jī)');
}
}
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è)計(jì)模式與開發(fā)實(shí)踐》