解开请求调用者和接受者之间的耦合关系。
- 菜单程序例子
- 点击按钮,发送请求,但是不知道接收者是谁,也不知道接收者做怎样的处理。
<button id="button1">点击按钮1</button>
<button id="button2">点击按钮2</button>
<button id="button3">点击按钮3</button>
// js
var button1 = document.getElementById( 'button1' ),
var button2 = document.getElementById( 'button2' ),
var button3 = document.getElementById( 'button3' );
var setCommand = function( button, command ){
button.onclick = function(){
command.execute();
}
};
2.按下按钮会发生一些事情是不变的,具体发生什么事情是可变的。
var MenuBar = {
refresh: function(){
console.log( '刷新菜单目录' );
}
};
var SubMenu = {
add: function(){
console.log( '增加子菜单' );
},
del: function(){
console.log( '删除子菜单' );
}
};
// 把 行为封装到命令类中
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 );
- js中命令模式
简化了上面的操作,没用引入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 );
- 撤销和重做
可以把命令先保存在堆栈。执行重做命令时,从堆栈中依次取出命令并执行。 - 宏命令
一次可以执行一批命令。这些都是先用一个变量将命令先缓存下来,当执行命令时,遍历这个对象,并依次执行命令。
网友评论