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

来源:互联网 发布:怎么剔除异常数据 编辑:程序博客网 时间:2024/06/03 22:52

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

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

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

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

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



原创粉丝点击