1.概述
这个模式也比较简单,书中没有提到。用于恢复上次操作结果等场景,比如数据库回滚等。这个模式有三个参与的实体:
Originator:知道如何保存自己的对象。
Caretaker:知道Originator何时以及为何保存并恢复自己的对象。
Memento:由Originator进行读写,并且Caretaker完成维护的对象
2.实例
首先,我们创建一个Memento:
1: class Memento {2: private String state;3:4: public Memento(String stateToSave) { state = stateToSave; }5: public String getSavedState() { return state; }6: }7:8:里面有我们希望保存的状态的存取方法。
然后我们创建Originator:
1: class Originator {2: private String state;3: /* lots of memory consumptive private data that is not necessary to define the4: * state and should thus not be saved. Hence the small memento object. */5:6: public void set(String state) {7: System.out.println("Originator: Setting state to "+state);8: this.state = state;9: }10:11: public Memento saveToMemento() {12: System.out.println("Originator: Saving to Memento.");13: return new Memento(state);14: }15: public void restoreFromMemento(Memento m) {16: state = m.getSavedState();17: System.out.println("Originator: State after restoring from Memento: "+state);18: }19: }20:提供了保存状态、恢复状态以及设置状态的接口。
最后我们再实现Caretaker:
1: class Caretaker {2: private ArrayList savedStates = new ArrayList();3:4: public void addMemento(Memento m) { savedStates.add(m); }5: public Memento getMemento(int index) { return savedStates.get(index); }6: }7:在这里面提供了对Memento的维护的相关存取接口。
到此,我们就可以写一段测试程序来看看这个备忘录模式是不是能正常工作:
1: class MementoExample {2: public static void main(String[] args) {3: Caretaker caretaker = new Caretaker();4:5: Originator originator = new Originator();6: originator.set("State1");7: originator.set("State2");8: caretaker.addMemento( originator.saveToMemento() );9: originator.set("State3");10: caretaker.addMemento( originator.saveToMemento() );11: originator.set("State4");12:13: originator.restoreFromMemento( caretaker.getMemento(1) );14: }15: }16:17:18:3.UML