c# 备忘录模式_C#教程

分享到:
结构图:


Memento类:保存状态的容器

    class Memento
    {
        public string State { get; set; }
        public Memento(string state)
        {
            this.State = state;
        }
    }

Caretaker是保存Memento类:

    class Caretaker
    {
        public Memento Memento { get; set; }
    }

Originator类就是需要保存状态的类:

    class Originator
    {
        public string State { get; set; }
        public Memento CreateMemento()
        {
            return (new Memento(State));
        }
        public void SetMemento(Memento memento)
        {
            State = memento.State;
        }
        public void Show()
        {
            Console.WriteLine("State:" + State);
        }
    }

 主函数调用:

    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.ReadKey();
        }
    }
   
昵    称:
验证码: