不同版本的命令模式

命令模式的意图是把请求封装为队形,从而分离请求的发起者和请求的接收者的耦合关系,下面是三种不同版本的命令模式


//对象关联的命令模式
// 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 = { //变化内容
// open:function(){
// alert('打开电视机');
// },
// close:function(){
// alert('关闭电视机');
// }
// }
// var openTvCommand = { //电视命令对象
// execute:function(){
// this.open();
// },
// undo:function(){
// this.close();
// }
// };
// var setCommand = function(receiver,command){
// var obj = createAndConnect(command,receiver); //电视对象关联其命令对象
// document.getElementById('execute').addEventListener('click',function(){
// obj.execute();
// },false);
// document.getElementById('undo').addEventListener('click',function(){
// obj.undo();
// },false);
// }
// setCommand(TV,openTvCommand);

// 面向类的命令模式
// var TV = { //变化内容
// open:function(){
// alert('打开电视机');
// },
// close:function(){
// alert('关闭电视机');
// }
// }
// var openTvCommand = function(receiver){ //初始化命令对象,命令对象里面应该有一个接受者
// 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对象,当命令对象执行execute和undo时,由TV对象接收

//闭包版本的命令模式
var TV = { //变化内容
open: function () {
alert('打开电视机');
},
close: function () {
alert('关闭电视机');
}
}
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设计模式与开发实践》

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容