1. 模式
定义:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。
分类:行为型模式
适用性
- Command 模式是回调(callback)机制的一个面向对象的替代品。所谓回调函数是指函数先在某处注册,而它将在稍后某个需要的时候被调用。
- 在不同的时刻指定、排列和执行请求。Command 对象可以有一个与初始请求无关的生存期。
- 支持取消操作。需要定义 Unexecute 操作来取消 Execute 操作调用的效果。
- 支持修改日志,这样当系统崩溃时,这些修改可以被重做一遍。
- 用构建在原语操作上的高层操作构造一个系统。例如构建事务(Transaction)系统。
2. 任务
- 场景:顾客去餐厅点餐,服务员将菜单交与厨师处理 clientA,clientB,invoker,recieverA,recieverB
- 顾客
clientA: {
param: ["doingA1", "doingA2"];
}
clientB: {
param: ["doingA1", "doingB1"];
}
- 厨师
recieverA:{
action:function(something){
console.log(`A...${something}`);
}
}
recieverB:{
action:function(something){
console.log(`B...${something}`);
}
}
- 服务员
invoker:{
addCommand:function (command){
this.commands.push(command);
}
excute:function(command){}
}
3. JS 实现
let clientA = {
param: ["doingA1", "doingA2"],
};
let clientB = {
param: ["doingA1", "doingB1"],
};
let recieverA = {
action: function (something) {
console.log(`A...${something}`);
},
};
let recieverB = {
action: function (something) {
console.log(`B...${something}`);
},
};
let invoker = {
commands: [],
addCommand: function (command) {
this.commands.push(command);
},
excute: function () {
for (let i = 0; i < this.commands.length; i++) {
this.commands[i]();
}
},
};
let commandA = function () {
return recieverA.action(clientA.param);
};
let commandB = function () {
return recieverB.action(clientB.param);
};
invoker.addCommand(commandA);
invoker.addCommand(commandB);
invoker.excute();