备忘录模式

本文最后更新于 2025年7月27日 上午

在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态

角色

  1. 备忘录创建者:负责创建一个备忘录,可以记录,恢复自身的内部状态, 同时还可以根据需要决定备忘录存储自身的哪些内部状态
  2. 备忘录角色:用于存储创建者的内部状态,并且可以防止其他对象访问备忘录
  3. 备忘录存储角色:负责存储备忘录,不能队备忘录的内容进行操作和访问,只能够将备忘录传递给其他对象

实现备忘录模式

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class Memento {
private String content ;

public Memento(String content){
this.content = content;
}
public String getContent(){
return content;
}
}

public class NoteCaretaker{
private List<Memonto>mementoList = new ArrayList<>();
private int index = 0;
public void saveMemento(Memento memento){
mementoList.add(memento);
index = mementoList.size() -1 ;
}
public Memento getPreMemento(){
index = index > 0 ? --index : index ;
Memento memento = mementoList.get(index);
return memento;
}
}

public class NoteEditText {
private String content ;
public String getContent(){
return content;
}
public void setContent(String content){
this.content = content ;
System.out.println("写入的内容是:"+content);
}

public Memento createMemento(){
Memento memento = new Memento(content);
return memento;
}
public void restore(Memento memento){
this.setContent(memento.getContent());
}
}

// 调用
public class Test{
public static void main(String[] args){
NoteEditText noteEditText = new NoteEditText();
NoteCaretaker noteCaretaker = new NoteCaretaker();

noteEditText.setContent("something to record 1 ");
noteCaretaker.saveMemento(noteEditText.createMemento());

noteEditText.setContent("something to record 2 ");
noteCaretaker.saveMemento(noteEditText.createMemento());

noteEditText.restore(noteCaretaker.getPreMemento());
}
}

总结

备忘录模式是一种 行为型设计模式 ,通过将对象的内部状态提取到一个独立的“备忘录对象”中,使得对象可以在未来被恢复到特定的历史状态。它 既保留了封装性 ,又为状态管理提供了清晰的机制,尤其适用于实现“撤销(undo)”、“历史记录”、“快照恢复”等功能。


备忘录模式
http://gadoid.io/2025/07/27/备忘录模式/
作者
Codfish
发布于
2025年7月27日
许可协议