备忘录模式

存档恢复

场景


对象可以存档,复原,回到历史状态

代码


Sample
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
class Originator {
private String state;

public String getState() {
return state;
}

public Memento save() {
return new Memento(state);
}

public void recovery(Memento memento) {
state = memento.getState();
}
}

class Memento {
private String state;

public Memento(String state) {
this.state = state;
}

public String getState() {
return state;
}
}

class MementoKeeper {
private List<Memento> list = new ArrayList<>();

public void add(Memento state) {
list.add(state);
}

public Memento get(int index) {
return list.get(index);
}
}

特征


带状态的对象提供保存/恢复功能
存档以单独对象存在
存档管理者提供存储和查找

应用


java.io.Serializable 序列化/反序列化