命令模式
特点
- 执行命令时,发布者和执行者分开
- 中间加入命令对象,作为中转站
- 特别类似于 组合模式,但是设计意图不同,组合模式用于区分整体与部分,命令模式为了弱化发布者与执行者之间的关联关系
介绍
- 将命令的接受者与命令的发送者解耦。
- 通俗的讲就是命令的发送者,在自己的代码块中不需要将其他基础对象作为依赖。
- 所有对外的请求,都使用固定的对象进行绑定。只保留自己的执行过程,对于不属于自己的部分进行控制移交,全部交给 Command 类,对外只知道有 excute 方法而已。
- 好处:命令者不需要关注接收者内部代码究竟如何实现,自己只知道自己需要执行一个命令,并不需要考虑命令的执行者究竟是谁
demo
更多详细代码
function Command(info) {
this.info = info;
this.reserves = [];
}
Command.prototype.addReceiver = function (reserve) {
this.reserves.push(reserve);
};
Command.prototype.cmd = function () {
for (let reserve of this.reserves) {
reserve.excute();
}
};
Command.prototype.getInfo = function () {
return this.info;
};
function Reserve(name, action) {
this.name = name;
this.action = action;
}
Reserve.prototype.excute = function () {
console.log(`${this.name} ${this.action}`);
};
function Invoker(name) {
this.name = name;
this.command = null;
}
Invoker.prototype.setCommand = function (command) {
this.command = command;
};
Invoker.prototype.invoke = function () {
console.log(`${this.name} 发布命令 ${this.command.getInfo()}`);
this.command.cmd();
};
const reserve1 = new Reserve("茶壶", "烧水");
const reserve2 = new Reserve("杯子", "盛水");
const command1 = new Command("喝水");
command1.addReceiver(reserve1);
command1.addReceiver(reserve2);
const user = new Invoker("user1");
user.setCommand(command1);
user.invoke();