备忘录模式

备忘录模式(Memento Pattern)保存一个对象的某个状态,以便在适当的时候恢复对象

Class Diagram

  • Memento 包含了要被恢复的对象的状态
  • Originator 创建并在 Memento 对象中存储状态
  • Caretaker 对象负责从 Memento 中恢复对象的状态

Implementation

备忘录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Memento {
private String state;

public Memento(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
public class CareTaker {
private List<Memento> mementoList = new ArrayList<Memento>();

public void add(Memento memento){
this.mementoList.add(memento);
}

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

备忘录记录者

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

private String state;

public String getState() {
return state;
}

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

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

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

public void show() {
System.out.println("State : " + state);
}
}

测试类

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

@Test
public void test() throws Exception {

CareTaker careTaker = new CareTaker();

// 初始化并建立备忘录
Originator o = new Originator();
o.setState("init");
o.show();
careTaker.add(o.createMemento());

// 状态错误
o.setState("error");
o.show();

// 从备忘录中恢复
o.setMemento(careTaker.get(0));
o.show();

}

}

Example

  • java.io.Serializable

Reflence