zoukankan      html  css  js  c++  java
  • 备忘录模式

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

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

      #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();
            }

  • 相关阅读:
    iOS uitableView响应事件被拦截
    《数据结构、算法与应用》8.(顺序查找数组中第一个出现指定元素的位置)
    Codeforces 475B Strongly Connected City 强连通裸题
    hdu1501&&poj2192 Zipper(DFS)
    hdu 4031 Attack(树状数组区间更新单点求值&暴力)
    Bash Shell 流程控制 —— select
    Longest Valid Parentheses
    HDU 2955 Robberies
    浅谈 Objective-C Associated Objects
    浅谈 Objective-C Associated Objects
  • 原文地址:https://www.cnblogs.com/ningxinjie/p/12185100.html
Copyright © 2011-2022 走看看