二十.备忘录模式

备忘录模式:

       Memento:在不破坏封装性的前提下,捕获一个对象内部状态,并在该对象之外保存这个状态。以便将对象恢复到原先保存状态。

 

Demo

       //备忘录模式

   class Program

    {

       static void Main(string[] args)

       {

           Originator o = new Originator();

           o.State = "On";

           o.Show();

            //实例化管理者,保存状态

           Caretaker c = new Caretaker();

           c.Mement0 = o.CreateMemento();

 

           o.State = "off";

           o.Show();

           //恢复状态

           o.SetMemento(c.Mement0);

           o.Show();

 

           Console.ReadKey();

       }

    }

 

       class Originator

    {

       private string state;//保存的属性

       public string State

       {

           get { return state; }

           set { state = value; }

       }

       public Memento CreateMemento()//创建备忘录,将数据导入实例化一个Memento对象

       {

           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 Memento(string state)

        {

            this.state = state;

        }

        public string State

        {

            get { return state; }

        }

    }

 

//管理者类

   class Caretaker

    {

       private Memento memento;

       public Memento Mement0//得到或设置备忘录

       {

           get { return memento; }

           set { memento = value; }

       }

    }

 

posted @ 2010-09-01 20:30  耀哥  阅读(318)  评论(0编辑  收藏  举报