概念
- 执行命令时,发布者和执行者分开
- 中间加入命令对象,作为中转站

演示
class Receiver {
exec() {
console.log('执行')
}
}
class Command {
constructor(receiver) {
this.receiver = receiver;
}
cmd() {
console.log('触发命令')
this.receiver.exec()
}
}
class Invoker {
constructor(command) {
this.command = command
}
invoke() {
console.log('开始')
this.command.cmd()
}
}
let soldier = new Receiver()
let trumpeter = new Command(soldier)
let general = new Invoker(trumpeter)
general.invoke()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
JS中的应用
- 网页富文本编辑器操作,浏览器封装了一个命令对象
document.execCommand('bold')document.execCommand('undo')
设计原则验证