

新闻资讯
技术学院备忘录模式通过发起人、备忘录和管理者三者协作,在不破坏封装性的前提下实现对象状态的保存与恢复;例如文本编辑器中利用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;
}
}
使用方式:
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
备忘录模式适合以下情况:
需要注意的问题:
基本上就这些。用好备忘录模式,能让状态管理更清晰,也更容易实现撤销类功能。关键是把状态保存和恢复的逻辑隔离好,保持对象封装性。