Appearance
命令模式
有时需要发送请求执行操作,但是不知道接收者,也不知道具体的操作请求,此时用命令模式。
命令模式由三种角色构成:
- 发布者invoker,发出命令,调用命令对象,不知道如何执行,谁执行
- 接收者receiver,提供对应接口处理请求,不知道谁发起请求
- 命令对象command,接收命令,调用接收者对应接口处理发布者的请求
javascript
class Receiver{
// 接收类
execute(){
console.log("")
}
}
class Command{
constructor(receiver){
this.receiver = receiver
}
// 命令类
execute(){
console.log("")
this.recerver.execute()
}
}
class Invoker{
constructor(command){
this.command = command
}
// 发布类
execute(){
console.log("")
this.command.execute()
}
}
const order = new Command(new Receiver())
const client = new Invoker(order)
client.order()
小例子
javascript
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("选项卡执行")
}
}
const Swipe = {
execute(){
console.log("轮播执行")
}
}
const macroCommand = new MacroCommand()
macroCommand.add(Tabs)
macroCommand.add(Swipte)
macroCommand.execute()