跳到主要内容

命令模式(Command Pattern)

命令模式(Command Pattern)是一种行为型设计模式,它用于将请求或操作封装为独立的对象,从而允许将请求参数化、延迟执行或将请求存储在队列中,以及支持撤销操作。命令模式的核心思想是将命令的请求者(调用者)与命令的执行者(接收者)解耦,使系统更加灵活和可扩展。

在命令模式中,有以下关键角色:

命令(Command):代表一个特定的操作,包括操作的接收者和执行操作的方法。命令通常包含一个 execute 方法,用于执行操作。

具体命令(Concrete Command):实现了命令接口,封装了对接收者的操作调用。

命令接收者(Receiver):执行实际操作的对象,也就是命令的执行者。

命令调用者(Invoker):负责创建和存储命令对象,以及调用命令执行操作。

场景

实现撤销和重做功能:通过将每个操作封装为一个命令对象,可以轻松实现撤销和重做功能。

实现事务管理:在数据库系统中,命令模式可用于实现事务,将一系列数据库操作封装为命令对象,以便控制事务的提交或回滚。

实现队列任务:命令模式可用于构建队列任务处理系统,其中每个命令对象代表一个待执行的任务。

遥控器控制设备:用于创建遥控器或控制面板,将各种操作封装为命令,以便控制设备的开关、音量等功能。

实现

// 命令接口
class Command {
execute() {}
}

// 具体命令 - 开灯
class LightOnCommand extends Command {
constructor(light) {
super();
this.light = light;
}

execute() {
this.light.turnOn();
}
}

// 具体命令 - 关灯
class LightOffCommand extends Command {
constructor(light) {
super();
this.light = light;
}

execute() {
this.light.turnOff();
}
}

// 命令接收者 - 电灯
class Light {
turnOn() {
console.log("Light is on");
}

turnOff() {
console.log("Light is off");
}
}

// 命令调用者 - 遥控器
class RemoteControl {
constructor() {
this.command = null;
}

setCommand(command) {
this.command = command;
}

pressButton() {
this.command.execute();
}
}

// 客户端代码
const light = new Light();
const remoteControl = new RemoteControl();

const lightOnCommand = new LightOnCommand(light);
const lightOffCommand = new LightOffCommand(light);

remoteControl.setCommand(lightOnCommand);
remoteControl.pressButton(); // 打开电灯

remoteControl.setCommand(lightOffCommand);
remoteControl.pressButton(); // 关闭电灯

在上面的示例中,我们有 Command 接口和两个具体命令类 LightOnCommand 和 LightOffCommand,它们分别代表打开和关闭电灯的命令。Light 类是命令的接收者,负责执行实际操作。

RemoteControl 类是命令调用者,它可以设置命令并按下按钮执行命令。通过命令模式,遥控器与电灯的操作被解耦,可以轻松地切换不同的命令对象以执行不同的操作。

命令模式有助于实现撤销、重做、队列任务等功能,同时降低了命令的发送者和接收者之间的耦合度。