描述
主要目的是保存一个对象的某个状态,以便在适当的时候恢复对象
适用
通俗的讲下:假设有原始类A,A中有各种属性,A可以决定需要备份的属性,备忘录类B是用来存储A的一些内部状态,类C呢,就是一个用来存储备忘录的,且只能存储,不能修改等操作
UML

示例
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| 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; } } 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; } } class Original{ private String value; public String getValue(){ return value; } public void setValue(String value){ this.value = value; } public Original(String value){ setValue(value); } public Memento createMemento(){ return new Memento(value); } public void restoreMemento(Memento memento){ this.value = memento.getValue(); } }
public class Test { public static void printMsg(String msg){ System.out.println(msg); } public static void main(String[] args){ Original orig = new Original("test"); Storage storage = new Storage(orig.createMemento()); Test.printMsg("初始化状态为: "+orig.getValue()); orig.setValue("A"); Test.printMsg("修改后状态为: "+orig.getValue()); orig.restoreMemento(storage.getMemento()); Test.printMsg("恢复后状态为: "+orig.getValue()); } }
|