前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >备忘录模式

备忘录模式

作者头像
WindrunnerMax
发布2020-11-24 11:19:39
3270
发布2020-11-24 11:19:39
举报
文章被收录于专栏:Czy‘s BlogCzy‘s Blog

备忘录模式

备忘录模式Memento Pattern是在不破坏封装性的前提下,将对象当前的内部状态保存在对象之外,以便以后当需要时能将该对象恢复到原先保存的状态。备忘录模式又叫快照模式,是一种对象行为型模式。

描述

备忘录模式是关于捕获和存储对象的当前状态的方式,以便以后可以平滑地恢复它。

优点

  • 提供了一种可以恢复状态的机制,当用户需要时能够比较方便地将数据恢复到某个历史的状态。
  • 实现了内部状态的封装,除了创建它的发起类之外,其他对象都不能够访问这些状态信息。
  • 简化了发起类,发起类不需要管理和保存其内部状态的各个备份,所有状态信息都保存在备忘录中,并由管理者进行管理,这符合单一职责原则。

缺点

  • 资源消耗大,如果要保存的内部状态信息过多或者特别频繁,将会占用比较大的内存资源。

适用环境

  • 需要保存/恢复数据的相关状态场景。
  • 提供一个可回滚的操作。

实现

代码语言:javascript
复制
// 以文本编辑器为例,该编辑器会不时地保存状态,并且可以根据需要进行恢复。

class EditorMemento { // memento对象将能够保持编辑器状态
    constructor(content) {
        this._content = content;
    }
    
    getContent() {
        return this._content;
    }
}

class Editor {
    constructor(){
        this._content = "";
    }
    
    type(words) {
        this._content = `${this._content} ${words}`;
    }
    
    getContent() {
        return this._content;
    }
    
    save() {
        return new EditorMemento(this._content);
    }
    
    restore(memento) {
        this._content = memento.getContent();
    }
}

(function(){
    const editor = new Editor()

    editor.type("This is the first sentence.");
    editor.type("This is second.");

    const saved = editor.save();

    editor.type("And this is third.")

    console.log(editor.getContent()); // This is the first sentence. This is second. And this is third.

    editor.restore(saved);

    console.log(editor.getContent()); // This is the first sentence. This is second.
})();

每日一题

代码语言:javascript
复制
https://github.com/WindrunnerMax/EveryDay

参考

代码语言:javascript
复制
https://github.com/Byronlee/Design-patterns
https://www.runoob.com/design-pattern/memento-pattern.html
https://github.com/sohamkamani/javascript-design-patterns-for-humans#-memento
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-11-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 备忘录模式
    • 描述
      • 优点
      • 缺点
      • 适用环境
    • 实现
      • 每日一题
        • 参考
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档