备忘录模式
保存一个对象的某个状态,以便在适当的时候恢复对象,更形象些的说法是备份模式
UML
Java
- 实现备忘录类Memento:
public class Memento { private String value; public Memento(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
- 实现存储备忘录的Storage类:
public class Storage { private Memento memento; public Storage(Memento memento) { this.memento = memento; } public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
- 实现原始原始类,里面有需要保存的属性value及创建一个备忘录Memento实例:
public class Original { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Original(String value) { this.value = value; } public Memento createMemento(){ return new Memento(value); } public void restoreMemento(Memento memento){ this.value = memento.getValue(); } }
- 测试代码:
public class MementoTest { public static void main(String[] args) { // 创建原始类 Original origi = new Original("egg"); // 创建备忘录 Storage storage = new Storage(origi.createMemento()); // 修改原始类的状态 System.out.println("init state:" + origi.getValue()); origi.setValue("chick"); System.out.println("updated state:" + origi.getValue()); // 回复原始类的状态 origi.restoreMemento(storage.getMemento()); System.out.println("restore state:" + origi.getValue()); } }
- 测试结果:
init state:egg updated state:chick restore state:egg