备忘录模式通过发起人、备忘录和管理者三者协作,在不破坏封装性的前提下实现对象状态的保存与恢复;例如文本编辑器中利用History管理多个TextMemento实例,实现撤销功能;适用于需支持撤销、历史记录等场景,但需注意性能开销与深拷贝问题。

备忘录模式是一种行为设计模式,用于在不破坏封装的前提下保存和恢复对象的内部状态。在JavaScript中,这种模式特别适用于需要撤销操作、历史记录或状态快照的场景,比如文本编辑器、表单填写、游戏存档等。
备忘录模式通常包含三个主要部分:
以下是一个简单的文本编辑器使用备忘录模式实现撤销功能的例子:
// 发起人:文本编辑器
class TextEditor {
constructor() {
this.content = '';
}
// 修改内容
write(text) {
this.content += text;
}
// 创建备忘录(保存当前状态)
save() {
return new TextMemento(this.content);
}
// 恢复状态
restore(memento) {
this.content = memento.getContent();
}
}
// 备忘录:保存编辑器状态
class TextMemento {
constructor(content) {
this.savedContent = content;
}
getContent() {
return this.savedContent;
}
}
// 管理者:负责管理多个备忘录(如历史记录)
class History {
constructor() {
this.mementos = [];
}
push(memento) {
this.mementos.push(memento);
}
pop() {
return this.mementos.pop() || null;
}
}
使用方式:
立即学习“Java免费学习笔记(深入)”;
const editor = new TextEditor();
const history = new History();
editor.write("Hello");
history.push(editor.save()); // 保存状态
editor.write(" World");
history.push(editor.save()); // 保存状态
editor.write("!");
console.log(editor.content); // 输出: Hello World!
// 撤销一次
editor.restore(history.pop());
console.log(editor.content); // 输出: Hello World
// 再撤销一次
editor.restore(history.pop());
console.log(editor.content); // 输出: Hello
备忘录模式适合以下情况:
需要注意的问题:
基本上就这些。用好备忘录模式,能让状态管理更清晰,也更容易实现撤销类功能。关键是把状态保存和恢复的逻辑隔离好,保持对象封装性。
以上就是JavaScript备忘录模式_状态保存与恢复的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号