请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
怎么说,大概就是古时候皇帝下达一些命令,比如赏赐黄金万两,加官进爵什么的,然后他就不管了,手底下的人自然会根据命令去完成相应的事情。
class Invoker {
constructor(commands) {
this.commands = commands
}
execCommand(command) {
console.log('祈求者(触发者)开始请求')
this.commands[command].execute()
}
}
class Command {
constructor(receiveds) {
this.receiveds = receiveds
}
execute() {
console.log('命令者执行请求')
if(Object.keys(this.receiveds).length > 0) {
const receiveds = this.receiveds
for(const key in receiveds) {
receiveds[key].execute()
}
}
}
}
class Received {
constructor(action) {
this.action = action
}
execute() {
console.log('接收者执行请求:', this.action)
}
}
const take = new Received('取钱')
const give = new Received('送钱')
const gold = new Command({take, give})
const invoker = new Invoker({gold})
invoker.execCommand('gold')