介绍
命令模式,将请求封装成对象,将命令的发送者和接受者解耦。本质上是对方法调用的封装。
主要概念:
- 命令接口(Command Interface):定义命令对象的接口,通常包含一个执行(execute)方法。
- 具体命令(Concrete Command):实现命令接口,封装了具体的命令逻辑,负责执行请求。
- 命令发送者(Invoker):负责创建命令对象并设置其接收者,将命令对象发送给执行者。
- 命令接收者(Receiver):负责执行具体的操作或请求。。
ts代码
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| interface Command { execute(): void; }
class LightOnCommand implements Command { private light: Light;
constructor(light: Light) { this.light = light; }
execute() { this.light.turnOn(); } }
class LightOffCommand implements Command { private light: Light;
constructor(light: Light) { this.light = light; }
execute() { this.light.turnOff(); } }
class Light { turnOn() { console.log("开灯"); } turnOff() { console.log("关灯"); } }
class RemoteControl { private commands: Command[] = [];
setCommand(command: Command) { this.commands.push(command); }
executeCommand() { this.commands.forEach((command) => command.execute()); this.commands = []; } }
const remoteControl = new RemoteControl(); const light = new Light(); const lightOnCommand = new LightOnCommand(light); const lightOffCommand = new LightOffCommand(light); remoteControl.setCommand(lightOnCommand); remoteControl.setCommand(lightOffCommand); remoteControl.executeCommand();
|