在不破坏封装性的前提下, 捕获一个对象的内部状态, 并在该对象之外保存这个状态
备忘录模式
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
| class Originator { private string state; public string State{get;set;} public Memento CreateMemento() { return new Memento(state); } public void SetMemento(Memento memento) { state = memento.State; } public void Show() { Console.WriteLine("State = " + state); } }
class Memento { private string state; public string State{get;} public Memento(string state) { this.state = state; } }
class Caretaker { private Memento memento; public Memento Memento{get; set;} }
Originator o = new Originator(); o.State = "On"; o.Show();
Caretaker c = new Caretaker(); c.Memento = o.CreateMemento();
o.State = "Off"; o.Show();
o.SetMemento(c.Memento); o.Show();
|