第77章 命令模式
题目:命令模式——可撤销的文本编辑器操作
实现一个支持撤销和重做的文本编辑器核心逻辑。每个操作(插入、删除)被封装为命令对象,通过命令队列统一执行与回滚。
设计思路
定义Command接口,包含do()和undo()方法。编辑器持有undoStack和redoStack。执行命令时调用do()并压入撤销栈;撤销时弹出命令执行undo(),再压入重做栈。核心亮点:使用TypeScript接口约束命令结构,并用泛型数组管理栈。
核心代码(TypeScript)
interface Command {
do(): void;
undo(): void;
}
class TextEditor {
private content = '';
private undoStack: Command[] = [];
private redoStack: Command[] = [];
execute(cmd: Command) {
cmd.do();
this.undoStack.push(cmd);
this.redoStack.length = 0; // 新命令清空重做栈
}
undo() {
const cmd = this.undoStack.pop();
if (cmd) {
cmd.undo();
this.redoStack.push(cmd);
}
}
redo() {
const cmd = this.redoStack.pop();
if (cmd) {
cmd.do();
this.undoStack.push(cmd);
}
}
getText() { return this.content; }
setText(t: string) { this.content = t; }
}
class InsertCommand implements Command {
constructor(private editor: TextEditor, private text: string) {}
do() { this.editor.setText(this.editor.getText() + this.text); }
undo() { this.editor.setText(this.editor.getText().slice(0, -this.text.length)); }
}
class DeleteCommand implements Command {
private removed = '';
constructor(private editor: TextEditor, private count: number) {}
do() {
this.removed = this.editor.getText().slice(-this.count);
this.editor.setText(this.editor.getText().slice(0, -this.count));
}
undo() { this.editor.setText(this.editor.getText() + this.removed); }
}
运行验证
依次执行:插入"Hello" → 插入" World" → 删除5个字符 → 撤销 → 撤销 → 重做。最终结果为"Hello",验证命令栈行为正确。
注意事项
深拷贝问题:如果命令状态包含对象,撤销时需快照,否则引用篡改会导致状态错乱。本案例使用字符串不可变特性简化实现。
成功要点
命令模式将操作与执行解耦,新增操作类型(如替换)只需扩展Command实现,无需修改编辑器主体。撤销栈和重做栈的协作是状态管理的精髓。