备忘录模式

1 概念

1 定义

保存一个对象的某种状态,以便在适当的时候来恢复对象

类型:行为型

2 应用场景

保存及恢复数据相关业务场景

3 优缺点

优点:

  • 为用户提供一种可恢复的机制
  • 存档信息的封装

缺点:

  • 资源占用

2 代码实现

场景:网站上发布博客,支持暂存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Data
@AllArgsConstructor
public class Article {
private String title;
private String content;

public ArticleMemento saveToMemento() {
return new ArticleMemento(this.title, this.content);
}

public void undoFromMemento(ArticleMemento articleMemento) {
this.title = articleMemento.getTitle();
this.content = articleMemento.getContent();
}
}
1
2
3
4
5
6
@AllArgsConstructor
@Getter
public class ArticleMemento {
private String title;
private String content;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 利用栈的先进后出来做备忘录
*/
public class ArticleMementoManager {

private final Stack<ArticleMemento> ARTICLE_MEMENTO_STACK = new Stack<ArticleMemento>();

public ArticleMemento getMemento()
{
return ARTICLE_MEMENTO_STACK.pop();
}

public void addMemento(ArticleMemento articleMemento)
{
ARTICLE_MEMENTO_STACK.push(articleMemento);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Test {

public static void main(String[] args) {
ArticleMementoManager articleMementoManager = new ArticleMementoManager();
Article article= new Article("如影随行的设计模式A","内容A");

// 版本1保存到备忘录
ArticleMemento articleMemento = article.saveToMemento();
articleMementoManager.addMemento(articleMemento);
System.out.println("标题:"+article.getTitle()+" 内容:"+article.getContent()+" 暂存成功");
System.out.println("完整信息:"+article);

System.out.println("============修改文章start============");
article.setTitle("如影随行的设计模式B");
article.setContent("内容B");
System.out.println("============修改文章end============");

// 版本2保存到备忘录
articleMemento = article.saveToMemento();
articleMementoManager.addMemento(articleMemento);
System.out.println("标题:"+article.getTitle()+" 内容:"+article.getContent()+" 暂存成功");
System.out.println("完整信息:"+article);

// 回退到版本2
System.out.println("============暂存回退start============");
System.out.println("回退出栈1次");
articleMemento = articleMementoManager.getMemento();
article.undoFromMemento(articleMemento);

// 回退到版本1
System.out.println("回退出栈2次");
articleMemento = articleMementoManager.getMemento();
article.undoFromMemento(articleMemento);
System.out.println("============暂存回退end============");
System.out.println("完整信息:"+article);
}
}

输出:

标题:如影随行的设计模式A 内容:内容A 暂存成功
完整信息:Article(title=如影随行的设计模式A, content=内容A)
============修改文章start============
============修改文章end============
标题:如影随行的设计模式B 内容:内容B 暂存成功
完整信息:Article(title=如影随行的设计模式B, content=内容B)
============暂存回退start============
回退出栈1次
回退出栈2次
============暂存回退end============
完整信息:Article(title=如影随行的设计模式A, content=内容A)


备忘录模式
http://example.com/备忘录模式/
作者
Panyurou
发布于
2023年10月4日
许可协议