标签:sum tst gen 封装 show format span mamicode space
备忘录模式:
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
说白了,就是对对象数据做保存和还原,并防止外部对数据修改。主要用于需要数据回滚的情况。
一、UML结构图
二、示例代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace 备忘录模式 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Originator o = new Originator(); 13 o.State1 = "A1"; 14 o.State2 = 2; 15 o.State3 = "B3"; 16 Console.WriteLine(string.Format("当前原数数据状态:\n{0,5}", o.ToString())); 17 Console.WriteLine(); 18 19 //保存当前状态 20 Caretaker c = new Caretaker(); 21 c.Memento= o.SaveInfo(); 22 Console.WriteLine(string.Format("已保存原始数据状态:\n S1={0},S2={1}", c.Memento.GetState1,c.Memento.GetState2)); 23 Console.WriteLine(); 24 25 Console.WriteLine("现在更改还原数据..."); 26 o.State1 = "A2"; 27 o.State2 = 3; 28 o.State3="B2"; 29 Console.WriteLine(string.Format("更改原数数据状态后:\n{0,5}",o.ToString())); 30 Console.WriteLine(); 31 32 Console.WriteLine("现在还原数据..."); 33 o.Recove(c.Memento); 34 Console.WriteLine(string.Format("还原后状态:\n{0,5}", o.ToString())); 35 36 Console.WriteLine(); 37 Console.Read(); 38 39 } 40 } 41 42 /// <summary> 43 /// 原始对象 44 /// </summary> 45 public class Originator 46 { 47 private string m_State1; 48 /// <summary> 49 /// 状态1 50 /// </summary> 51 public string State1 52 { 53 get { return m_State1; } 54 set { m_State1 = value; } 55 } 56 57 private int m_State2; 58 /// <summary> 59 /// 状态2 60 /// </summary> 61 public int State2 62 { 63 get { return m_State2; } 64 set { m_State2 = value; } 65 } 66 67 private string m_State3; 68 /// <summary> 69 /// 状态3 70 /// </summary> 71 public string State3 72 { 73 get { return m_State3; } 74 set { m_State3 = value; } 75 } 76 77 public Memento SaveInfo() 78 { 79 return new Memento(m_State1, m_State2); 80 } 81 82 /// <summary> 83 /// 还原 84 /// </summary> 85 /// <param name="m"></param> 86 public void Recove(Memento m) 87 { 88 if (m != null) 89 { 90 m_State1 = m.GetState1; 91 m_State2 = m.GetState2; 92 } 93 } 94 95 public override string ToString() 96 { 97 return string.Format("State1={0},State2={1},State3={2}", m_State1, m_State2, m_State3); 98 } 99 } 100 101 /// <summary> 102 /// 备忘录(用于保存原始对象部分信息,不需要外界知道原始对象的全部内容) 103 /// 备忘录对象只提供两个接口,一个存储信息,一个读取信息。 104 /// </summary> 105 public class Memento 106 { 107 private string m_State1; 108 private int m_State2; 109 110 public Memento(string s1, int s2) 111 { 112 m_State1 = s1; 113 m_State2 = s2; 114 } 115 116 public String GetState1 117 { 118 get { return m_State1; } 119 } 120 public int GetState2 121 { 122 get { return m_State2; } 123 } 124 } 125 126 /// <summary> 127 /// 管理者类,只用于对备忘录进行保存和读取。 128 /// </summary> 129 public class Caretaker 130 { 131 Memento m_Memento = null; 132 133 public Memento Memento 134 { 135 get { return m_Memento; } 136 set { m_Memento = value; } 137 } 138 139 } 140 141 }
标签:sum tst gen 封装 show format span mamicode space
原文地址:https://www.cnblogs.com/qiupiaohujie/p/11972098.html