命令模式通过封装请求为对象,实现调用者与执行者的解耦;示例中遥控器(调用者)通过命令控制灯(接收者)的开关,支持扩展、撤销与队列操作。
命令模式是一
种行为设计模式,它将请求或操作封装成对象,从而使你可以用不同的请求、队列、日志来参数化对象。这种模式的核心思想是把“做什么”和“谁去做”解耦,让调用者不需要知道具体的执行细节。
命令模式通常包含以下几个角色:
下面是一个简单的命令模式实现,模拟一个遥控器控制灯的开关:
// 接收者:灯
class Light {
turnOn() {
console.log("灯打开了");
}
turnOff() {
console.log("灯关闭了");
}
}
// 命令接口(抽象类,JS中用函数或类表示)
class Command {
execute() {}
}
// 具体命令:开灯命令
class TurnOnLightCommand extends Command {
constructor(light) {
super();
this.light = light;
}
execute() {
this.light.turnOn();
}
}
// 具体命令:关灯命令
class TurnOffLightCommand extends Command {
constructor(light) {
super();
this.light = light;
}
execute() {
this.light.turnOff();
}
}
// 调用者:遥控器
class RemoteControl {
setCommand(command) {
this.command = command;
}
pressButton() {
this.command.execute();
}
}
// 客户端使用
const light = new Light();
const turnOn = new TurnOnLightCommand(light);
const turnOff = new TurnOffLightCommand(light);
const remote = new RemoteControl();
remote.setCommand(turnOn);
remote.pressButton(); // 输出:灯打开了
remote.setCommand(turnOff);
remote.pressButton(); // 输出:灯关闭了
使用命令模式可以带来以下好处:
命令模式在前端开发中有不少实用场景:
基本上就这些。命令模式通过封装行为,让程序更具弹性,特别是在需要动态配置操作或支持撤销机制时特别有用。