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

实现
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; }
public Memento createMemento() { return new Memento(state); }
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(); }
}
|