15-JavaScript设计模式——命令模式

命令模式:一种封装方法调用的方式。

命令模式的作用:消除 命令调用者 和 命令执行者 之间的耦合(在两者之间建立一个解耦器)。

命令模式分类: 简单命令模式 复杂命令模式 (事务等) 闭包命令模式

命令模式必须实现一个接口。

// 先看一个 简单命名模式
// 接口
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();// 命令开启了



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值