某些对象发送请求,但是并不知道请求的接受者是谁,也不知道被请求的操作是什么。------所以需要 松耦合的方式来设计,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。
同时,命令模式还具备支持 撤销、排队等操作。
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 );
二。宏命令。与组合模式 相同感觉。
var closeDoorCommand = {
excute: function(){
console.log('关门')
}
}
var openPcCommand = {
excute: function(){
console.log('打开电脑')
}
}
var openMusiceCommand = {
excute: function(){
console.log('打开音乐')
}
}
var MacroCommand = function(){
return {
commandsList: [],
add: function( command ){
this.commandsList.push( command );
},
excute: function(){
for( var i = 0, command; command = this.commandsList[ i++ ]){
command.excute();
}
}
}
}
var macroCommand = MacroCommand();
macroCommand.add( closeDoorCommand );
macroCommand.add( openPcCommand );
macroCommand.add( openMusiceCommand );
macroCommand.excute();