备忘录模式(Memento Pattern)
在不暴露对象实现细节的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便之后恢复对象为先前的状态。
结构图:
角色:
- 发起人(Originator):类可以生成自身状态的快照, 也可以在需要时通过快照恢复自身状态。
- 备忘录(Memento):存储发起人状态快照,在进行恢复时提供给发起人需要的状态。
- 管理者(Caretaker):备忘录管理者负责存储备忘录。
适用场景:
- 对象状态需要防丢失、撤销、恢复等场景下。
优点:
- 提供了一种可以恢复状态的机制,可以方便的回滚到某个版本。
- 不破坏对象封装情况的前提下创建对象状态快照。
缺点:
- 如果频繁创建备份或者备份的数据结构过大会消耗大量的内存。
代码(C#)
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
public class Memento { private string _state;
public Memento(string state) { _state = state; }
public string GetState() { return _state; } }
public class Originator { private string _state;
public Originator(string state) { _state = state; }
public Memento CreateMemento() { return (new Memento(_state)); } public string GetState() { return _state; }
public void RestoreMemento(Memento memento) { _state = memento.GetState(); } }
public class Caretaker { public List<Memento> Memento = new List<Memento>();
public void Add(Memento memento) { Memento.Add(memento); }
public Memento Get(int index) { return Memento[index]; } }
Originator a = new Originator("A"); Originator b = new Originator("B");
Caretaker m = new Caretaker(); m.Memento.Add(a.CreateMemento()); m.Memento.Add(b.CreateMemento());
b.RestoreMemento(m.Get(0)); Console.WriteLine(b.GetState());
|
最后
备忘录模式的实现很灵活,也没有很固定的实现方式,在不同的业务需求、不同编程语言下,代码实现可能都不大一样。只要满足在不违背封装原则的前提下,进行对象的备份和恢复就算是备忘录模式。