命令模式通过将请求封装为对象,使程序支持可撤销操作和任务队列;其核心角色包括命令、具体命令、接收者和调用者;JavaScript中可用于遥控器示例,实现灯的开关与撤销功能,并广泛应用于菜单系统、操作历史、任务队列等场景。

命令模式是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。命令模式还能支持撤销操作。在JavaScript中,这种模式非常适合处理用户交互、任务队列和可撤销操作等场景。
命令模式通常包含以下几个角色:
下面是一个使用JavaScript实现的命令模式例子,模拟一个简单的遥控器控制灯的开关。
// 接收者:灯
class Light {
  turnOn() {
    console.log("灯打开了");
  }
  
  turnOff() {
    console.log("灯关闭了");
  }
}
// 命令接口(抽象)
class Command {
  execute() {
    throw new Error("子类必须实现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 RemoteControl {
  constructor() {
    this.command = null;
  }
  setCommand(command) {
    this.command = command;
  }
  pressButton() {
    if (this.command) {
      this.command.execute();
    }
  }
}
// 使用示例
const light = new Light();
const lightOn = new LightOnCommand(light);
const lightOff = new LightOffCommand(light);
const remote = new RemoteControl();
remote.setCommand(lightOn);
remote.pressButton(); // 输出:灯打开了
remote.setCommand(lightOff);
remote.pressButton(); // 输出:灯关闭了
命令模式的一个优势是容易实现撤销功能。我们可以在命令对象中添加undo方法。
立即学习“Java免费学习笔记(深入)”;
// 修改具体命令,增加undo支持
class LightOnCommand extends Command {
  constructor(light) {
    super();
    this.light = light;
  }
  execute() {
    this.light.turnOn();
  }
  undo() {
    this.light.turnOff();
  }
}
class LightOffCommand extends Command {
  constructor(light) {
    super();
    this.light = light;
  }
  execute() {
    this.light.turnOff();
  }
  undo() {
    this.light.turnOn();
  }
}
// 扩展调用者以支持撤销
class RemoteControl {
  constructor() {
    this.command = null;
  }
  setCommand(command) {
    this.command = command;
  }
  pressButton() {
    if (this.command) {
      this.command.execute();
    }
  }
  pressUndo() {
    if (this.command && typeof this.command.undo === 'function') {
      this.command.undo();
    }
  }
}
// 演示撤销
remote.setCommand(lightOn);
remote.pressButton(); // 灯打开了
remote.pressUndo();   // 灯关闭了
命令模式在前端开发中有多种用途:
基本上就这些。通过封装请求为对象,命令模式让程序更灵活、可扩展,也更容易维护复杂的行为逻辑。
以上就是使用JavaScript实现一个命令模式_js设计模式的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号