命令模式通过封装操作为对象实现撤销与重做功能,核心角色包括Command、ConcreteCommand、Receiver和Invoker;以文本编辑器为例,InsertCommand和DeleteCommand分别记录插入与删除操作的位置及内容,确保可逆;CommandManager维护undoStack和redoStack栈,执行新命令时压入undo栈并清空redo栈,调用undo时将命令从undo栈弹出并压入redo栈,redo则相反;TextEditor作为接收者提供insert、delete等实际方法;客户端通过CommandManager触发命令,实现灵活的操作历史管理;该模式适用于需状态回溯的场景如表单、绘图、游戏指令等。

在前端开发中,命令模式是一种非常实用的行为设计模式,特别适合实现撤销(Undo)和重做(Redo)功能。通过将操作封装为对象,命令模式让执行、撤销、记录操作变得灵活可控。下面介绍如何使用 JavaScript 实现一个支持撤销与重做的命令模式系统。
命令模式包含四个基本角色:
以文本编辑器为例,我们模拟“插入文字”和“删除文字”的撤销重做功能。
每个命令需要实现 execute 和 undo 方法,保证操作可逆。
立即学习“Java免费学习笔记(深入)”;
class InsertCommand {
constructor(editor, text) {
this.editor = editor;
this.text = text;
this.position = editor.getContent().length; // 记录插入位置
}
execute() {
this.editor.insert(this.text);
}
undo() {
this.editor.deleteAt(this.position, this.text.length);
}
}
class DeleteCommand {
constructor(editor, start, length) {
this.editor = editor;
this.start = start;
this.length = length;
this.deletedText = this.editor.getContent().slice(start, start + length); // 保存被删内容
}
execute() {
this.editor.deleteAt(this.start, this.length);
}
undo() {
this.editor.insertAt(this.start, this.deletedText);
}
}
调用者负责执行命令,并维护撤销和重做栈。每次执行新命令时,清空重做栈,确保操作历史线性。
class CommandManager {
constructor() {
this.undoStack = [];
this.redoStack = [];
}
execute(command) {
command.execute();
this.undoStack.push(command);
this.redoStack = []; // 新操作后,清除重做历史
}
undo() {
if (this.undoStack.length === 0) return;
const command = this.undoStack.pop();
command.undo();
this.redoStack.push(command);
}
redo() {
if (this.redoStack.length === 0) return;
const command = this.redoStack.pop();
command.execute();
this.undoStack.push(command);
}
}
接收者是实际处理数据的对象,比如文本编辑器。客户端通过调用者触发命令。
class TextEditor {
constructor() {
this.content = '';
}
insert(text) {
this.content += text;
}
insertAt(pos, text) {
this.content =
this.content.slice(0, pos) + text + this.content.slice(pos);
}
deleteAt(start, length) {
this.content =
this.content.slice(0, start) +
this.content.slice(start + length);
}
getContent() {
return this.content;
}
}
// 使用示例
const editor = new TextEditor();
const manager = new CommandManager();
manager.execute(new InsertCommand(editor, 'Hello'));
manager.execute(new InsertCommand(editor, ' World'));
console.log(editor.getContent()); // "Hello World"
manager.undo();
console.log(editor.getContent()); // "Hello"
manager.redo();
console.log(editor.getContent()); // "Hello World"
基本上就这些。只要每个命令保存足够的上下文信息,就能精准还原状态。这种结构清晰、扩展性强,适用于表单操作、绘图工具、游戏指令等多种场景。
以上就是JavaScript命令模式_撤销重做功能设计的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号