前言
假设有一个快餐店,而我是该餐厅的点餐服务员,那么我一天的工作应该是这样的:当某位客人点餐或者打来订餐电话后,我会把他的需求都写在清单上,然后交给厨房,客人不用关心是哪些厨师帮他炒菜。我们餐厅还可以满足客人需要的定时服务,比如客人可能当前正在回家的路上,要求1个小时后才开始炒他的菜,只要订单还在,厨师就不会忘记。客人也可以很方便地打电话来撤销订单。另外如果有太多的客人点餐,厨房可以按照订单的顺序排队炒菜。这些记录着订餐信息的清单,便是命令模式中的命令对象
命令模式的用途
命令模式是最简单和优雅的模式之一,命令模式中的命令(command)指的是一个执行某些特定事情的指令。
命令模式最常见的应用场景是:有时候需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么。此时希望用一种松耦合的方式来设计程序,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。
举例:
拿订餐来说,客人需要向厨师发送请求,但是完全不知道这些厨师的名字和联系方式,也不知道厨师炒菜的方式和步骤。命令模式把客人订餐的请求封装成command对象,也就是订餐中的订单对象。这个对象可以在程序中被四处传递,就像订单可以从服务员手中传到厨师的手中。这样一来,客人不需要知道厨师的名字,从而解开了请求调用者和请求接收者之间的耦合关系。
另外,相对于过程化的请求调用,command对象拥有更长的生命周期。对象的生命周期是跟初始请求无关的,因为这个请求已经被封装在了command对象的方法中,成为了这个对象的行为。我们可以在程序运行的任意时刻去调用这个方法,就像厨师可以在客人预定1个小时之后才帮他炒菜,相当于程序在1个小时之后才开始执行command对象的方法。
点击按钮例子
假设我们正在编写一个用户界面程序,该用户界面上至少有数十个Button按钮。因为项目比较复杂,所以我们决定让某个程序员负责绘制这些按钮,而另外一些程序员则负责编写点击按钮后的具体行为,这些行为都将被封装在对象里
<body>
<button id="button1">点击按钮1</button>
<button id="button2">点击按钮2</button>
<button id="button3">点击按钮3</button>
</body>
<script>
var button1 = document.getElementById( 'button1' ),
var button2 = document.getElementById( 'button2' ),
var button3 = document.getElementById( 'button3' );
</script>
接下来定义setCommand函数,setCommand函数负责往按钮上面安装命令。可以肯定的是,点击按钮会执行某个command命令,执行命令的动作被约定为调用command对象的execute()方法。虽然还不知道这些命令究竟代表什么操作,但负责绘制按钮的程序员不关心这些事情,他只需要预留好安装命令的接口,command对象自然知道如何和正确的对象沟通:
var setCommand = function( button, command ){
button.onclick = function(){
command.execute();
}
};
最后,负责编写点击按钮之后的具体行为的程序员总算交上了他们的成果,他们完成了刷新菜单界面、增加子菜单和删除子菜单这几个功能,这几个功能被分布在MenuBar和SubMenu这两个对象中:
var MenuBar = {
refresh: function(){
console.log( ’刷新菜单目录’ );
}
};
var SubMenu = {
add: function(){
console.log( ’增加子菜单’ );
},
del: function(){
console.log( ’删除子菜单’ );
}
};
在让button变得有用起来之前,我们要先把这些行为都封装在命令类中:
var RefreshMenuBarCommand = function( receiver ){
this.receiver = receiver;
};
RefreshMenuBarCommand.prototype.execute = function(){
this.receiver.refresh();
};
var AddSubMenuCommand = function( receiver ){
this.receiver = receiver;
};
AddSubMenuCommand.prototype.execute = function(){
this.receiver.add();
};
var DelSubMenuCommand = function( receiver ){
this.receiver = receiver;
};
DelSubMenuCommand.prototype.execute = function(){
console.log( ’删除子菜单’ );
};
最后就是把命令接收者传入到command对象中,并且把command对象安装到button上面:
var refreshMenuBarCommand = new RefreshMenuBarCommand( MenuBar );
var addSubMenuCommand = new AddSubMenuCommand( SubMenu );
var delSubMenuCommand = new DelSubMenuCommand( SubMenu );
setCommand( button1, refreshMenuBarCommand );
setCommand( button2, addSubMenuCommand );
setCommand( button3, delSubMenuCommand );
JavaScript中的命令模式
也许我们会感到很奇怪,所谓的命令模式,看起来就是给对象的某个方法取了execute的名字。引入command对象和receiver这两个无中生有的角色无非是把简单的事情复杂化了,即使不用什么模式,用下面寥寥几行代码就可以实现相同的功能。
var bindClick = function( button, func ){
button.onclick = func;
};
var MenuBar = {
refresh: function(){
console.log( ’刷新菜单界面’ );
}
};
var SubMenu = {
add: function(){
console.log( ’增加子菜单’ );
},
del: function(){
console.log( ’删除子菜单’ );
}
};
bindClick( button1, MenuBar.refresh );
bindClick( button2, SubMenu.add );
bindClick( button3, SubMenu.del );
通过闭包的命令模式
var setCommand = function( button, func ){
button.onclick = function(){
func();
}
};
var MenuBar = {
refresh: function(){
console.log( ’刷新菜单界面’ );
}
};
var RefreshMenuBarCommand = function( receiver ){
return function(){
receiver.refresh();
}
};
var refreshMenuBarCommand = RefreshMenuBarCommand( MenuBar );
setCommand( button1, refreshMenuBarCommand );
撤销命令
小球运动案例
<body>
<div id="ball" style="position:absolute; background:#000; width:50px; height:50px"></div>
输入小球移动后的位置:<input id="pos"/>
<button id="moveBtn">开始移动</button>
</body>
<script>
var ball = document.getElementById( 'ball' );
var pos = document.getElementById( 'pos' );
var moveBtn = document.getElementById( 'moveBtn' );
moveBtn.onclick = function(){
var animate = new Animate( ball );
animate.start( 'left', pos.value, 1000, 'strongEaseOut' );
};
</script>
如果文本框输入200,然后点击moveBtn按钮,可以看到小球顺利地移动到水平方向200px的位置。现在我们需要一个方法让小球还原到开始移动之前的位置。当然也可以在文本框中再次输入-200,并且点击moveBtn按钮,这也是一个办法,不过显得很笨拙。页面上最好有一个撤销按钮,点击撤销按钮之后,小球便能回到上一次的位置。在给页面中增加撤销按钮之前,先把目前的代码改为用命令模式实现:
var ball = document.getElementById( 'ball' );
var pos = document.getElementById( 'pos' );
var moveBtn = document.getElementById( 'moveBtn' );
var MoveCommand = function( receiver, pos ){
this.receiver = receiver;
this.pos = pos;
};
MoveCommand.prototype.execute = function(){
this.receiver.start( 'left', this.pos, 1000, 'strongEaseOut' );
};
var moveCommand;
moveBtn.onclick = function(){
var animate = new Animate( ball );
moveCommand = new MoveCommand( animate, pos.value );
moveCommand.execute();
};
接下来增加撤销按钮:
<body>
<div id="ball" style="position:absolute; background:#000; width:50px; height:50px"></div>
输入小球移动后的位置:<input id="pos"/>
<button id="moveBtn">开始移动</button>
<button id="cancelBtn">cancel</button> <! --增加取消按钮-->
</body>
撤销操作的实现一般是给命令对象增加一个名为unexecude或者undo的方法,在该方法里执行execute的反向操作。在command.execute方法让小球开始真正运动之前,我们需要先记录小球的当前位置,在unexecude或者undo操作中,再让小球回到刚刚记录下的位置,代码如下:
<script>
var ball = document.getElementById( 'ball' );
var pos = document.getElementById( 'pos' );
var moveBtn = document.getElementById( 'moveBtn' );
var cancelBtn = document.getElementById( 'cancelBtn' );
var MoveCommand = function( receiver, pos ){
this.receiver = receiver;
this.pos = pos;
this.oldPos = null;
};
MoveCommand.prototype.execute = function(){
this.receiver.start( 'left', this.pos, 1000, 'strongEaseOut' );
this.oldPos = this.receiver.dom.getBoundingClientRect()[ this.receiver.propertyName ];
// 记录小球开始移动前的位置
};
MoveCommand.prototype.undo = function(){
this.receiver.start( 'left', this.oldPos, 1000, 'strongEaseOut' );
// 回到小球移动前记录的位置
};
var moveCommand;
moveBtn.onclick = function(){
var animate = new Animate( ball );
moveCommand = new MoveCommand( animate, pos.value );
};
moveCommand.execute();
cancelBtn.onclick = function(){
moveCommand.undo(); // 撤销命令
};
</script>
重做命令
命令模式可以用来实现播放录像功能
<html>
<body>
<button id="replay">播放录像</button>
</body>
<script>
var Ryu = {
attack: function(){
console.log( '攻击' );
},
defense: function(){
console.log( '防御' );
},
jump: function(){
console.log( '跳跃' );
},
crouch: function(){
console.log( '蹲下' );
}
};
var makeCommand = function( receiver, state ){ // 创建命令
return function(){
receiver[ state ]();
}
};
var commands = {
"119": "jump", // W
"115": "crouch", // S
"97": "defense", // A
"100": "attack" // D
};
var commandStack = []; // 保存命令的堆栈
document.onkeypress = function( ev ){
var keyCode = ev.keyCode,
command = makeCommand( Ryu, commands[ keyCode ] );
if ( command ){
command(); // 执行命令
commandStack.push( command ); // 将刚刚执行过的命令保存进堆栈
}
};
document.getElementById( 'replay' ).onclick = function(){ // 点击播放录像
var command;
while( command = commandStack.shift() ){ // 从堆栈里依次取出命令并执行
command();
}
};
</script>
</html>
可以看到,当我们在键盘上敲下W、A、S、D这几个键来完成一些动作之后,再按下Replay按钮,此时便会重复播放之前的动作。
宏命令
宏命令是一组命令的集合,通过执行宏命令的方式,可以一次执行一批命令。想象一下,家里有一个万能遥控器,每天回家的时候,只要按一个特别的按钮,它就会帮我们关上房间门,顺便打开电脑并登录QQ。
var closeDoorCommand = {
execute: function(){
console.log( ’关门’ );
}
};
var openPcCommand = {
execute: function(){
console.log( ’开电脑’ );
}
};
var openQQCommand = {
execute: function(){
console.log( ’登录QQ' );
}
};
var MacroCommand = function(){
return {
commandsList: [],
add: function( command ){
this.commandsList.push( command );
},
execute: function(){
for ( var i = 0, command; command = this.commandsList[ i++ ]; ){
command.execute();
}
}
}
};
var macroCommand = MacroCommand();
macroCommand.add( closeDoorCommand );
macroCommand.add( openPcCommand );
macroCommand.add( openQQCommand );
macroCommand.execute();