设计模式十五(备忘录模式)

1.备忘录模式其实就是保存一个对象的状态方便恢复到某个状态。它一般用在功能比较复杂,但需要维护或记录属性的历史的类。

 

2.图解

 

3.代码展示

 

namespace 备忘录模式
{
    class Program
    {
        static void Main(string[] args)
        {

            Originator o = new Originator();
            o.State = "On";
            o.Show();

            Caretaker c = new Caretaker();
            c.Memento = o.CreateMemento();

            o.State = "Off";
            o.Show();

            o.SetMemento(c.Memento);
            o.Show();

            Console.Read();

        }
    }

    class Originator
    {
        private string state;
        public string State
        {
            get { return state; }
            set { state = value; }
        }

        public Memento CreateMemento()
        {
            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 Memento
        {
            get { return memento; }
            set { memento = value; }
        }
    }


}

 

posted @ 2010-11-30 23:17  yu_liantao  阅读(162)  评论(0)    收藏  举报