简介
命令模式:有时候需要向某些对象发送请求,但是并不知道请求的接受者是谁,也不知道被请求的操作是什么。需要 一种松耦合的方式来设计程序,是得发送者和接收者能够消除彼此之间的耦合关系。 命令模式有三个角色构成
- 发布者 invoker:发出命令,调用命令对象,不知道如何执行与谁执行
- 接收者 receiver:(提供对应接口处理请求,不知道谁发起请求)
- 命令对象 command:(接收命令,调用接收者对应接口处理发布者的请求)
示例
class Receiver {
//接收类
execute() {
console.log("接收者执行请求");
}
}
class Command {
//命令类
constructor(receiver) {
this.receiver = receiver;
}
execute() {
console.log("命令对象=》接受者如何处理");
this.receiver.execute();
}
}
class Invoker {
//发布类
constructor(command) {
this.command = command;
}
order() {
console.log("发布请求");
this.command.execute();
}
}
const order = new Command(new Receiver());
const client = new Invoker(order);
client.order();
示例 宏命令模式
/*
命令模式和组合模式的组合
一组命令的集合
*/
class MacroCommand {
constructor() {
this.list = [];
}
add(command) {
this.list.push(command);
}
execute() {
for (let item of this.list) {
item.execute();
}
}
}
const Tabs = {
execute() {
console.log("选项卡执行");
},
init() {
console.log("init");
},
getData() {
console.log("getData");
},
render() {
console.log("render");
},
};
const Swipe = {
execute() {
console.log("轮播执行");
},
};
const macroCommand = new MacroCommand();
macroCommand.add(Tabs);
macroCommand.add(Swipe);
macroCommand.execute();