c# 备忘录模式

时间:2021-10-31 07:30:08

结构图:
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类就是需要保存状态的类:

#3e6c2e5925fe9b9469f7a8dc10938e2c# 代码如下:


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