0%

设计模式-备忘录模式

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

类图

3Mzk4I.md.png

实现

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
public class Originator {

private String state;

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

/**
* 创建备忘录
*
* @return
*/
public Memento createMemento() {
return new Memento(state);
}

/**
* 恢复备忘录
*
* @param memento
*/
public void setMemento(Memento memento) {
state = memento.getState();
}

public void show() {
System.out.println("State=" + state);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Memento {

private String state;

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

public String getState() {
return state;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Caretaker {

private Memento memento;

public Memento getMemento() {
return memento;
}

public void setMemento(Memento memento) {
this.memento = memento;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Client {

public static void main(String[] args) {
Originator originator = new Originator();
originator.setState("on");
originator.show();

// 保存状态
Caretaker caretaker = new Caretaker();
caretaker.setMemento(originator.createMemento());

// 修改状态
originator.setState("off");
originator.show();

// 恢复初始状态
originator.setMemento(caretaker.getMemento());
originator.show();
}

}