首页 > web前端 > js教程 > 正文

JavaScript备忘录模式_状态持久化方案

夢幻星辰
发布: 2025-11-19 19:33:11
原创
579人浏览过
备忘录模式是一种通过发起者创建、管理者存储、备忘录封装状态的设计模式,用于实现对象状态的保存与恢复,适用于撤销操作、表单草稿、游戏存档等场景;在JavaScript中可结合localStorage实现持久化,确保页面刷新后仍能恢复历史状态,同时需注意性能、安全与存储优化。

javascript备忘录模式_状态持久化方案

备忘录模式在JavaScript中是一种实现状态持久化的设计模式,适用于需要保存和恢复对象历史状态的场景,比如撤销操作、表单草稿保存、游戏存档等。它通过将对象的内部状态封装起来,在不破坏封装性的前提下实现状态快照的存储与恢复。

什么是备忘录模式

备忘录模式(Memento Pattern)包含三个核心角色:

  • 发起者(Originator):拥有内部状态的对象,能创建备忘录来保存当前状态,也能通过备忘录恢复状态。
  • 备忘录(Memento):用于存储发起者状态的快照,通常只暴露必要的接口给管理者。
  • 管理者(Caretaker):负责保存和管理备忘录实例,但不修改或检查其内容。

这种模式的关键在于隔离状态访问权限,确保封装性不被破坏。

基础实现示例

下面是一个简单的JavaScript实现:

立即学习Java免费学习笔记(深入)”;

class Editor {
  constructor() {
    this.content = '';
  }
<p>// 设置内容
setContent(content) {
this.content = content;
}</p><p>// 获取当前状态(创建备忘录)
save() {
return new EditorMemento(this.content);
}</p><p>// 恢复到指定状态
restore(memento) {
this.content = memento.getContent();
}</p><p>getContent() {
return this.content;
}
}</p><p>class EditorMemento {
constructor(content) {
this.content = content;
}</p><p>getContent() {
return this.content;
}
}</p><p>class History {
constructor() {
this.states = [];
}</p><p>push(state) {
this.states.push(state);
}</p><p>pop() {
return this.states.pop();
}
}</p>
登录后复制

使用方式:

const editor = new Editor();
const history = new History();
<p>editor.setContent("第一版内容");
history.push(editor.save());</p><p>editor.setContent("第二版内容");
history.push(editor.save());</p><p>editor.setContent("第三版内容");</p>
                    <div class="aritcle_card">
                        <a class="aritcle_card_img" href="/ai/2189">
                            <img src="https://img.php.cn/upload/ai_manual/000/000/000/175680145915064.png" alt="绘蛙AI修图">
                        </a>
                        <div class="aritcle_card_info">
                            <a href="/ai/2189">绘蛙AI修图</a>
                            <p>绘蛙平台AI修图工具,支持手脚修复、商品重绘、AI扩图、AI换色</p>
                            <div class="">
                                <img src="/static/images/card_xiazai.png" alt="绘蛙AI修图">
                                <span>264</span>
                            </div>
                        </div>
                        <a href="/ai/2189" class="aritcle_card_btn">
                            <span>查看详情</span>
                            <img src="/static/images/cardxiayige-3.png" alt="绘蛙AI修图">
                        </a>
                    </div>
                <p>// 撤销一次
editor.restore(history.pop());
console.log(editor.getContent()); // 输出: 第二版内容</p><p>// 再撤销一次
editor.restore(history.pop());
console.log(editor.getContent()); // 输出: 第一版内容</p>
登录后复制

结合本地存储实现持久化

若希望页面刷新后仍保留历史记录,可将备忘录数据存入localStorage

扩展Editor类的save和restore方法:

class PersistentEditor {
  constructor(key) {
    this.content = '';
    this.key = key; // 存储键名
    this.loadFromStorage(); // 初始化时加载
  }
<p>setContent(content) {
this.content = content;
}</p><p>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);
}</p><p>getSavedStates() {
const data = localStorage.getItem(this.key);
return data ? JSON.parse(data) : [];
}</p><p>loadFromStorage() {
const states = this.getSavedStates();
if (states.length > 0) {
this.content = states[states.length - 1].content;
}
}</p><p>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));
}
}</p>
登录后复制

这样即使用户关闭浏览器再打开,也能恢复到最后一次保存的内容。

注意事项与优化建议

使用备忘录模式进行状态持久化时需注意以下几点:

  • 状态过大时频繁保存会影响性能,建议节流或仅在关键节点保存。
  • 敏感信息不应明文存储在localStorage中,考虑加密处理。
  • 可为备忘录添加时间戳、版本号等元信息,便于调试和用户选择恢复点。
  • 对于复杂状态对象,确保深拷贝以避免引用污染。
  • 移动端注意存储空间限制,定期清理旧快照。

基本上就这些。备忘录模式结构清晰,配合现代浏览器API可以轻松实现可靠的前端状态持久化机制。

以上就是JavaScript备忘录模式_状态持久化方案的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号