答案:通过命令模式将操作封装为对象,利用历史栈和重做栈实现撤销与重做功能。具体操作实现execute和undo方法,HistoryManager管理命令执行、撤销与重做流程,支持文本编辑等可逆操作,并注意合并输入、标记不可撤销命令及避免内存泄漏等问题。

实现一个支持撤销重做的命令模式历史管理器,核心是将用户的操作封装为“命令”对象,并通过历史栈记录这些命令的执行顺序。这样可以在不暴露具体业务逻辑的前提下,统一管理操作的撤销(undo)与重做(redo)。
定义命令接口
每个可撤销、可重做的操作都应实现统一的命令接口。该接口至少包含两个方法:
- execute():执行操作
- undo():撤销操作
如果需要支持重做,通常在执行新命令时清空重做栈,而重做操作则是将已撤销的命令重新执行。
示例:
class Command {
execute() {}
undo() {}
}
维护历史栈
使用两个数组分别存储已执行的命令和已被撤销的命令:
- history:存放已成功执行的命令(用于撤销)
- redoStack:存放被撤销的命令(用于重做)
当执行新命令时,将其加入 history 栈,并清空 redoStack;撤销时从 history 弹出命令并推入 redoStack;重做则相反。
关键逻辑:
class HistoryManager {
constructor() {
this.history = [];
this.redoStack = [];
}
execute(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);
}
}
实现具体命令
每一个用户操作(如修改文本、移动元素)都应封装为具体的命令类。命令需保存足够的上下文信息,以便正确执行和撤销。
例子:文本编辑命令
class TextEditCommand extends Command {
constructor(editor, oldText, newText) {
super();
this.editor = editor;
this.oldText = oldText;
this.newText = newText;
}
execute() {
this.editor.setText(this.newText);
}
undo() {
this.editor.setText(this.oldText);
}
}
使用时只需将命令交给 HistoryManager 执行:
const manager = new HistoryManager(); manager.execute(new TextEditCommand(editor, "hello", "world")); manager.undo(); // 恢复为 "hello" manager.redo(); // 变回 "world"
处理边界情况
实际应用中需注意几个细节:
- 连续输入等高频操作可合并为一个命令,避免历史过深
- 某些命令不可撤销(如删除敏感数据),应在设计时明确标记
- 命令对象持有对业务对象的引用,注意避免内存泄漏
- 异步操作需等待完成后再压入历史栈
基本上就这些。只要把操作抽象成命令,再用栈管理执行轨迹,撤销重做就很清晰了。










