备忘录模式

定义

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

代码

需要被恢复状态类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Originator {
private String state;

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}
//创建备忘录
public MyMemento createMemento(){
return new MyMemento(this.state);
}
//恢复备忘录
public void restoreMemento(MyMemento memento){
this.state = memento.getState();
}

}

备忘录角色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MyMemento {

private String state;

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

public String getState() {
return state;
}

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

备忘录管理

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

private MyMemento myMemento;

public MyMemento getMyMemento() {
return myMemento;
}

public void setMyMemento(MyMemento myMemento) {
this.myMemento = myMemento;
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MyMementoTest {

@Test
public void testMemento(){
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
originator.setState("before");
System.out.println(originator.getState());
caretaker.setMyMemento(originator.createMemento());
originator.setState("after");
System.out.println(originator.getState());
originator.restoreMemento(caretaker.getMyMemento());
System.out.println(originator.getState());
}
}
扩展

利用clone自身备份

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 CloneOriginator implements Cloneable{

private CloneOriginator backUp;
private String state;

public String getState() {
return state;
}

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

//备份
public void createMemento(){
this.backUp = this.clone();
}

public void restoreMemento(){
this.setState(this.backUp.getState());
}

@Override
protected CloneOriginator clone() {
CloneOriginator cloneOriginator;
try {
cloneOriginator = (CloneOriginator) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
cloneOriginator= null;
}
return cloneOriginator;
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
public class CloneOriginatorTest {
@Test
public void testCloneOriginator(){
CloneOriginator originator = new CloneOriginator();
originator.setState("before");
System.out.println(originator.getState());
originator.createMemento();
originator.setState("after");
System.out.println(originator.getState());
originator.restoreMemento();
System.out.println(originator.getState());
}
}