结构

备忘录模式

说明

Without violating encapsulation, capture and externalize an object’s internal state allowing the object to be restored to this state later.

在不破坏封装的条件下,将一个对象的状态捉住,并外部化,存储起来,从而可以在将来合适的时候把这个对象还原到存储起来的状态。

适用条件

需要保存对象在某一时刻的状态, 并在以后需要将对象恢复到这个状态; 同时又不希望暴露对象的实现细节, 破坏对象的封装性, 这是需要使用备忘录模式。

实现

public class Originator {

    private string _state;

    public void SetState(string state) {
        Console.WriteLine("Originator: setting momento to {0}", state);
        this._state = state;
    }

    public Momento SaveToMomento() {
        Console.WriteLine("Originator: saving to momento...");
        return new Originator.Momento(this._state);
    }

    public void RestoreFromMomento(Momento momento) {
        this._state = momento.State;
        Console.WriteLine("Originator: resotring from momento {0}", this._state);
    }
    
    public class Momento {

        private readonly string _state;

        internal Momento(string state) {
            this._state = state;
        }

        public string State {
            get {
                return this._state;
            }
        }
    }
}

class CareTaker {

    static void Main(string[] args) {
        IList<Originator.Momento> savedStates = new List<Originator.Momento>();

        var originator = new Originator();
        originator.SetState("State1");
        originator.SetState("State2");
        savedStates.Add(originator.SaveToMomento());
        originator.SetState("State3");
        savedStates.Add(originator.SaveToMomento());
        originator.SetState("State4");
        originator.RestoreFromMomento(savedStates[0]);

        Console.ReadKey();
    }
}