【设计模式-备忘录模式】

时间:2022-07-24
本文章向大家介绍【设计模式-备忘录模式】,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

【导读】浏览器网址框旁边会有一个点击可后退的按钮,点击之后可返回上一个浏览页面。这就是备忘录模式。利用某种数据结构保存之前的状态。

一、定义

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便以后当需要时能将该对象恢复到原先保存的状态。该模式又叫快照模式。

二、实例

比如日常编写word文档的时候,除了经常使用CV大法之外,还有撤回快捷键Ctrl+Z,可返回到上一个保存的状态。

文章对象:

public class Article {
    //标题
    private String title;
    //内容
    private String content;

    public Article(String title, String content) {
        this.title = title;
        this.content = content;
    }

    //撤回操作
    public void recover(ArticleMemento articleMemento) {
        this.title = articleMemento.getTitle();
        this.content = articleMemento.getContent();
    }

   //保存为一个缓存对象
    public ArticleMemento saveToCache(){
        ArticleMemento articleMemento = new ArticleMemento(title,content);
        return articleMemento;
    }

}

文章缓存对象:

1、属性跟文章对象一致   
public class ArticleMemento {

    private String title;
    private String content;

    public ArticleMemento(String title, String content) {
        this.title = title;
        this.content = content;
    }
}

缓存对象管理:

public class ArticleMementoManager {
    
    private static final Stack<ArticleMemento> stack = new Stack<ArticleMemento>();

    //将缓存对象入栈,相当于word的保存按钮
    public void addMemento(ArticleMemento articleMemento){
        System.out.println("将【"+articleMemento.toString()+"】进行暂存");
        stack.push(articleMemento);
    }

   //撤回,将最后一个缓存对象出栈,相当于撤回  
    public ArticleMemento recover(){
        ArticleMemento pop = stack.pop();
        return pop;
    }


}

利用栈先进后出的特性保存缓存对象。

测试代码:

ArticleMementoManager articleMementoManager = new ArticleMementoManager();
Article article = new Article("标题","内容");
System.out.println("新建一篇文章:【"+article.toString()+"】");
ArticleMemento articleMemento = article.saveToCache();
articleMementoManager.addMemento(articleMemento);

article.setContent("第一次修改内容");
System.out.println("将文章修改为:【"+article.toString()+"】");
articleMemento = article.saveToCache();
articleMementoManager.addMemento(articleMemento);

article.setTitle("第一次修改标题");
System.out.println("将文章修改为:【"+article.toString()+"】");


System.out.println("需要对文章进行第一次回退操作");
article.recover(articleMementoManager.recover());
System.out.println("回退之后文章为:【"+article.toString()+"】");

System.out.println("需要对文章进行第二次回退操作");
article.recover(articleMementoManager.recover());
System.out.println("回退之后文章为:【"+article.toString()+"】");

运行结果:

整体流程如下: