JavaScript命令模式_撤销重做功能实现

命令模式适合实现JavaScript撤销重做功能,通过封装操作为Command对象,利用历史栈和重做栈管理执行与回退。示例中TextEditor为接收者,InsertTextCommand实现具体操作,CommandManager管理命令执行、撤销、重做,支持清晰的逻辑控制与扩展。

在JavaScript中实现撤销和重做功能,命令模式是一个非常合适的设计模式。它将每个操作封装成一个对象,使得可以统一管理执行、撤销和重做逻辑。这种方式不仅结构清晰,还便于扩展和维护。

命令模式基本结构

命令模式的核心是把“请求”封装成对象。它通常包含以下几个部分:

  • Command(命令接口): 定义执行和撤销的方法,如 execute() 和 undo()
  • ConcreteCommand(具体命令): 实现具体操作,比如修改文本、移动元素等
  • Invoker(调用者): 负责调用命令,通常维护命令历史栈
  • Receiver(接收者): 真正执行业务逻辑的对象

通过这种结构,我们可以轻松记录操作历史,并支持撤销与重做。

实现撤销与重做的核心逻辑

要实现撤销和重做,关键是维护两个栈:

  • 历史栈(history): 存储已执行的命令
  • 重做栈(redoStack): 存储被撤销的命令

每次执行命令时,将其推入历史栈,并清空重做栈;撤销时,从历史栈弹出命令并执行其 undo 方法,同时推入重做栈;重做时则相反。

示例:实现一个简单的文本编辑器撤销/重做功能

// 接收者:处理实际逻辑
class TextEditor {
  constructor() {
    this.content = '';
  }

  insertText(text) {
    this.content += text;
  }

  deleteLastChar() {
    this.content = this.content.slice(0, -1);
  }
}

// 命令接口的抽象基类(JavaScript中用作模板)
class Command {
  constructor(editor) {
    this.editor = editor;
  }

  execute() {}
  undo() {}
}

// 具体命令:插入文本
class InsertTextCommand extends Command {
  constructor(editor, text) {
    super(editor);
    this.text = text;
  }

  execute() {
    this.editor.insertText(this.text);
  }

  undo() {
    this.editor.content = this.editor.content.slice(0, -this.text.length);
  }
}

// 调用者:管理命令执行与历史
class CommandManager {
  constructor() {
    this.history = [];
    this.redoStack = [];
  }

  executeCommand(command) {
    command.execute();
    this.history.push(command);
    this.redoStack = []; // 清空重做栈
  }

  undo() {
    if (this.history.length === 0) return;
    const command = this.history.pop();
    command.undo();
    this.redoStack.push(command);
  }

  redo() {
    if (this.redoStack.length === 0) return;
    const command = this.redoStack.pop();
    command.execute();
    this.history.push(command);
  }
}

使用示例

下面演示如何使用上述代码实现可撤销的操作:

const editor = new TextEditor();
const manager = new CommandManager();

// 执行操作
manager.executeCommand(new InsertTextCommand(editor, "Hello"));
manager.executeCommand(new InsertTextCommand(editor, " World"));

console.log(editor.content); // 输出: Hello World

// 撤销
manager.undo();
console.log(editor.content); // 输出: Hello

// 重做
manager.redo();
console.log(editor.content); // 输出: Hello World

扩展建议

在实际项目中,可以进一步优化:

  • 为命令添加唯一ID或时间戳,便于调试和日志追踪
  • 限制历史栈最大长度,防止内存溢出
  • 支持批量命令(CompositeCommand),如组合多个操作为一步
  • 结合事件机制,在撤销/重做时触发UI更新

基本上就这些。命令模式让撤销重做变得可控且可维护,特别适合富文本编辑器、图形工具、表单操作等场景。