命令模式:一种封装方法调用的方式。
命令模式的作用:消除 命令调用者 和 命令执行者 之间的耦合(在两者之间建立一个解耦器)。
命令模式分类: 简单命令模式 、 复杂命令模式 (事务等)、 闭包命令模式 。
命令模式必须实现一个接口。
// 先看一个 简单命名模式
// 接口
var CommandInterface = new JG.Interface('CommandInterface', ['execute']);
// 有一个按钮(obj),点击按钮 触发几个元素去执行一些动画效果
// 2个命令(1:start)(2: stop)
// 建立解耦器 StartCommand,该解耦器接收调用者消息obj,用该解耦器的方法 execute 来执行 调用者的 start() 方法
var StartCommand = function(obj){
this.ad = obj;
};
StartCommand.prototype.execute = function(){
this.ad.start();
};
var StopCommand = function(obj){
this.ad = obj;
};
StopCommand.prototype.execute = function(){
this.ad.stop();
};
// 执行
var stratCommand = new StartCommand(obj);
stratCommand.execute();
var stopCommand = new StopCommand(obj);
stopCommand.execute();
闭包命令模式
// 闭包命令模式
function MakeStart(obj){
return function(){
obj.start();
};
}
function MakeStop(obj){
return function(){
obj.stop();
};
}
var startCommand = new MakeStart(obj);
startCommand();// 命令开启了
var stopCommand = new MakeStart(obj);
stopCommand();// 命令开启了