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

命令模式是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。命令模式还能支持撤销操作。在JavaScript中,这种模式非常适合处理用户交互、任务队列和可撤销操作等场景。
基本结构
命令模式通常包含以下几个角色:
- 命令(Command):定义执行操作的接口,通常是一个有execute方法的对象。
- 具体命令(Concrete Command):实现命令接口,持有对接收者的引用,并在execute中调用接收者的方法。
- 接收者(Receiver):真正执行操作的对象。
- 调用者(Invoker):触发命令执行的对象,不直接与接收者交互。
简单实现示例
下面是一个使用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方法。
该系统采用多层模式开发,这个网站主要展示女装的经营,更易于网站的扩展和后期的维护,同时也根据常用的SQL注入手段做出相应的防御以提高网站的安全性,本网站实现了购物车,产品订单管理,产品展示,等等,后台实现了动态权限的管理,客户管理,订单管理以及商品管理等等,前台页面设计精致,后台便于操作等。实现了无限子类的添加,实现了动态权限的管理,支持一下一个人做的辛苦
立即学习“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(); // 灯关闭了
实际应用场景
命令模式在前端开发中有多种用途:
- 菜单或按钮系统:每个菜单项对应一个命令对象。
- 操作历史与撤销重做:将每次操作保存为命令,便于回退。
- 任务队列:将命令放入队列延迟执行或批量处理。
- 远程调用或消息系统:将请求序列化为命令对象传输。
基本上就这些。通过封装请求为对象,命令模式让程序更灵活、可扩展,也更容易维护复杂的行为逻辑。









