备忘录模式是一种通过发起者创建、管理者存储、备忘录封装状态的设计模式,用于实现对象状态的保存与恢复,适用于撤销操作、表单草稿、游戏存档等场景;在JavaScript中可结合localStorage实现持久化,确保页面刷新后仍能恢复历史状态,同时需注意性能、安全与存储优化。
备忘录模式在JavaScript中是一种实现状态持久化的设计模式,适用于需要保存和恢复对象历史状态的场景,比如撤销操作、表单草稿保存、游戏存档等。它通过将对象的内部状态封装起来,在不破坏封装性的前提下实现状态快照的存储与恢复。
备忘录模式(Memento Pattern)包含三个核心角色:
这种模式的关键在于隔离状态访问权限,确保封装性不被破坏。
下面是一个简单的JavaScript实现:
class Editor {
constructor() {
this.content = '';
}
// 设置内容
setContent(content) {
this.content = content;
}
// 获取当前状态(创建备忘录)
save() {
return new EditorMemento(this.content);
}
// 恢复到指定状态
restore(memento) {
this.content = memento.getContent();
}
getContent() {
return this.content;
}
}
class EditorMemento {
constructor(content) {
this.content = content;
}
getContent() {
return this.content;
}
}
class History {
constructor() {
this.states = [];
}
push(state) {
this.states.push(state);
}
pop() {
return this.states.pop();
}
}
使用方式:
const editor = new Editor(); const history = new History();editor.setContent("第一版内容"); history.push(editor.save());
editor.setContent("第二版内容"); history.push(editor.save());
editor.setContent("第三版内容");
// 撤销一次 editor.restore(history.pop()); console.log(editor.getContent()); // 输出: 第二版内容
// 再撤销一次 editor.restore(history.pop()); console.log(editor.getContent()); // 输出: 第一版内容
若希望页面刷新后仍保留历史记录,可将备忘录数据存入localStorage。
扩展Editor类的save和restore方法:
class PersistentEditor {
constructor(key) {
this.content = '';
this.key = key; // 存储键名
this.loadFromStorage(); // 初始化时加载
}
setContent(content) {
this.content = content;
}
save() {
const states = this.getSavedStates();
states.push({ content: this.content, timestamp: Date.now() });
localStorage.setItem(this.key, JSON.stringify(states));
return new EditorMemento(this.content);
}
getSave
dStates() {
const data = localStorage.getItem(this.key);
return data ? JSON.parse(data) : [];
}
loadFromStorage() {
const states = this.getSavedStates();
if (states.length > 0) {
this.content = states[states.length - 1].content;
}
}
restoreLast() {
const states = this.getSavedStates();
if (states.length < 2) return;
states.pop(); // 移除当前
const previous = states[states.length - 1];
this.content = previous.content;
localStorage.setItem(this.key, JSON.stringify(states));
}
}
这样即使用户关闭浏览器再打开,也能恢复到最后一次保存的内容。
使用备忘录模式进行状态持久化时需注意以下几点:
基本上就这些。备忘录模式结构清晰,配合现代浏览器API可以轻松实现可靠的前端状态持久化机制。