设计模式:备忘录模式

备忘录模式(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在改对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

namespace Memento
{
    public 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);
        }
    }
    public class Memento
    {
        private string state;
        public Memento(string state)
        {
            this.state = state;
        }
        public string State
        {
            get { return state; }
        }
    }
    public class Caretaker
    {
        private Memento memento;
        public Memento Memento
        {
            get { return memento; }
            set { memento = value; }
        }
    }
}
View Code

测试代码:

            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();
View Code

 

posted @ 2016-03-15 10:35  uptothesky  阅读(129)  评论(0编辑  收藏  举报