天天看點

備忘錄模式

定義:儲存一個對象的某個狀态,以便在适當的時候恢複對象。

優點: 

1、給使用者提供了一種可以恢複狀态的機制,可以使使用者能夠比較友善地回到某個曆史的狀态。

2、實作了資訊的封裝,使得使用者不需要關心狀态的儲存細節。

缺點:消耗資源。如果類的成員變量過多,勢必會占用比較大的資源,而且每一次儲存都會消耗一定的記憶體。

實作:

Memento 包含了要被恢複的對象的狀态。

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

Originator 建立并在 Memento 對象中存儲狀态。

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

Caretaker 對象負責從 Memento 中恢複對象的狀态。

class CareTaker
    {
        private Memento memento;
        public Memento Memento
        {
            get { return memento; }
            set { memento = value; }
        }
    }
      

調用:

Originator originator = new Originator();
            originator.State = "On";

            CareTaker careTaker = new CareTaker();
            careTaker.Memento = originator.CreateMemento();

            originator.State = "Off";

            originator.SetMemento(careTaker.Memento);
      

結果:

State=On
State=Off
Restoring state...
State=On