es6 语法学习 - 命令模式
一、基本概念
命令模式(Command Pattern)是一种行为设计模式,它将一个请求封装为一个对象,从而使你可以用不同的请求、队列或者日志请求来参数化其他对象。命令模式也支持可撤销的操作。
二、 优点
- 降低耦合:命令模式将请求调用者与请求接收者进行解耦,使得调用者和接收者之间没有直接的依赖关系。
- 扩展性高:如果要扩展新命令,只需定义新的命令对象即可,无需修改现有的代码。
- 易于组合命令:可以将多个命令组合成一个复合命令,然后一起执行。
- 支持撤销和重做:通过实现特定的命令类,可以方便地实现撤销和重做操作。
三、缺点
- 增加系统复杂性:由于引入了命令对象,可能会导致类的数量增加,从而增加系统的复杂性。
- 需要针对每个命令开发命令类:对于每个不同的命令,都需要开发一个与之对应的命令类,这可能会增加开发的工作量。
四、使用场景
- 当请求发送者和请求接收者之间需要解耦时,可以使用命令模式。
- 当需要支持撤销和重做操作时,可以使用命令模式。
- 当需要记录请求日志时,可以使用命令模式。
五、示例代码
以下是一个使用 ES6 语法的 JavaScript 示例,展示了命令模式的应用。
// 命令接口
class Command {
execute() {
throw new Error('Subclasses must implement execute()');
}
undo() {
// 可选:实现撤销操作
console.log('Undo operation not supported for this command.');
}
}
// 具体命令类:打开电灯命令
class OpenLightCommand extends Command {
constructor(light) {
super();
this.light = light;
}
execute() {
this.light.on();
console.log('Light is on.');
}
undo() {
this.light.off();
console.log('Light is off.');
}
}
// 电灯类
class Light {
on() {
console.log('Turning the light on.');
}
off() {
console.log('Turning the light off.');
}
}
// 调用者(遥控器)
class RemoteControl {
constructor() {
this.command = null;
}
setCommand(command) {
this.command = command;
}
pressButton() {
if (this.command) {
this.command.execute();
}
}
pressUndoButton() {
if (this.command && this.command.undo) {
this.command.undo();
}
}
}
// 客户端代码
const light = new Light();
const openLightCommand = new OpenLightCommand(light); // 具体命令类
const remote = new RemoteControl(); // 调用者
remote.setCommand(openLightCommand);
remote.pressButton(); // 输出: Turning the light on. Light is on.
remote.pressUndoButton(); // 输出: Turning the light off. Light is off.