备忘录模式

某类对象使用过程中,可能需要记录当前的状态,在需要的时候可以恢复到本次的状态,如果使用公有接口来保存对象,将会暴露对象的状态。由此备忘录模式出现。

(备忘录归根结底就是,实例化一个本身的类,将需要保存的数据存储在这里,这样使得原对象与备忘对象不指向同一个引用)

  #region 构建记忆主体类(与需要保存的属性等一致)
    class Memento
    {
        private string _name;
        private string _phone;
        private double _budget;

        public Memento(string name,string phone,double budget)
        {
            _name = name;
            _phone = phone;
            _budget = budget;
        }
        public string Name { get { return _name; } set { _name = value; } }
        public string Phone { get { return _phone; } set { _phone = value; } }
        public double Budget { get { return _budget; } set { _budget = value; } }
    }
    #endregion
 #region 需要使用的记忆类
    class ProspectMemory
    {
        private Memento memento;
        public Memento Memento { get { return memento; } set { memento = value; } }
    }
  #region 实际需要保存记忆的类
    class SalesProspect
    {
        private string _name;
        private string _phone;
        private double _budget;
        public string Name { get { return _name; } set { _name = value; } }
        public string Phone { get { return _phone; } set { _phone = value; } }
        public double Budget { get { return _budget; } set { _budget = value; } }
        public Memento SaveMemento()
        {
            return new 备忘录模式.Memento(Name, Phone, Budget);
        }
        public void RestoreMemento(Memento memento)
        {
            this._name = memento.Name;
            this._phone = memento.Phone;
            this._budget = memento.Budget;
        }
    }
    #endregion
  static void Main(string[] args)
        {
            SalesProspect s1 = new SalesProspect();
            s1.Name = "ximing";
            s1.Phone = "(0411)12345678";
            s1.Budget = 11000;

            ProspectMemory prospectmemory = new ProspectMemory();
            prospectmemory.Memento = s1.SaveMemento();//保存当前状态的记忆

            s1.Name = "dudu";
            Console.WriteLine(s1.Name);
            s1.RestoreMemento(prospectmemory.Memento);//恢复原始保存的记忆
            Console.WriteLine(s1.Name);
            Console.ReadKey();
        }

原文地址:https://www.cnblogs.com/ningxinjie/p/12185100.html