设计模式(十四)备忘录模式
备忘录(Memento),在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象回复到原先保存的状态。
Memento 模式比较适用于功能比较复杂,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性中的一小部分时,Originator 可以根据保存的 Memento 信息还原到前一状态。使用备忘录可以把复杂的对象内部信息对其他的对象屏蔽起来,从而可以恰当地保持封装的边界。

基本代码
1 // 发起人 2 class Originator 3 { 4 private string state; 5 public string State 6 { 7 get { return state; } 8 set { state = value; } 9 } 10 // 创建备忘录 11 public Memento CreateMemento() 12 { 13 return (new Memento(state)); 14 } 15 // 恢复备忘录 16 public void SetMemento(Memento memento) 17 { 18 state = memento.State; 19 } 20 public void Show() 21 { 22 Console.WriteLine("State=" + state); 23 } 24 } 25 26 // 备忘录 27 class Memento 28 { 29 private string state; 30 31 public Memento(string state) 32 { 33 this.state = state; 34 } 35 36 public string State 37 { 38 get { return state; } 39 } 40 } 41 42 // 管理者 43 class Caretaker 44 { 45 private Memento memento; 46 47 public Memento memento 48 { 49 get { return memento; } 50 set { memento = value; } 51 } 52 } 53 54 // 客户端 55 static void Main(string[] args) 56 { 57 Originator o = new Originator(); 58 o.State = "On"; 59 o.Show(); 60 61 // 保存状态 62 Caretaker c = new Caretaker(); 63 c.Memento = o.CreateMemento(); 64 65 o.State = "Off"; 66 o.Show(); 67 68 // 恢复状态 69 o.SetMemento(c.Memento); 70 o.Show(); 71 72 Console.Read(); 73 }
【例】游戏进度备忘

基本代码
1 class 游戏角色 2 { 3 // 保存角色状态 4 public RoleStateMemento SaveState() 5 { 6 return (new RoleStateMemento(vit, atk, def)); 7 } 8 9 // 恢复角色状态 10 public void RecoveryState(RoleStateMemento memento) 11 { 12 this.vit = memento.Vitality; 13 this.atk = memento.Attack; 14 this.def = memento.Defense; 15 } 16 17 } 18 19 // 角色状态存储箱类 20 class RoleStateMemento 21 { 22 private int vit; 23 private int atk; 24 private int def; 25 public RoleStateMemento(int vit, int atk, int def) 26 { 27 this.vit = vit; 28 this.atk = atk; 29 this.def = def; 30 } 31 32 // 生命力 33 public int Vitality 34 { 35 get { return vit; } 36 set { vit = value; } 37 } 38 // 攻击力 39 public int Attack 40 { 41 get { return atk; } 42 set { atk = value; } 43 } 44 // 防御力 45 public int Defense 46 { 47 get { return def; } 48 set { def = value; } 49 } 50 } 51 52 // 角色状态管理类 53 class RoleStateCaretaker 54 { 55 private RoleStateMemento memento; 56 public RoleStateMemento Memento 57 { 58 get { return memento; } 59 set { memento = value; } 60 } 61 }

浙公网安备 33010602011771号