命令模式(Command Pattern)
|
1 2 3 |
定义:请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。 目的:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。 场景:在一个快餐店,用户向服务员点餐。服务员将用户的需求记录在清单上。 |
|
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 |
// 1. 接收者:真正做事 const light = { turnOn() { console.log('灯亮了') } } // 2. 命令:封装“让这盏灯打开”的请求 class TurnOnCommand { constructor(light) { this.light = light } execute() { this.light.turnOn() } } // 3. 调用者:只负责执行命令 const remote = { press(command) { command.execute() } } // 使用 const command = new TurnOnCommand(light) remote.press(command) // 灯亮了 |

