memento 纪念品

memento仅存储对象状态 ,以便以后进行恢复。
public class OurObjectMemento
{
    int internalState;
    string anotherState;
    public int InternalState
    {
        get { return internalState; }
        set { internalState = value; }
    }
   public string AnotherState
    {
        get { return anotherState; }
        set { anotherState = value; }
    }

    public OurObjectMemento(int internalState,string anotherState)
    {
        this.internalState = internalState;
        this.anotherState = anotherState;
    }
}

public class OurObject
{

    int internalState=0;
    string anotherState="i know nothing";
    public OurObjectMemento CreateMemento()
    {
        return new OurObjectMemento(internalState, anotherState);
    }

    public void RestoreMemento(OurObjectMemento memento)
    {
        this.internalState = memento.InternalState;
        this.anotherState = memento.AnotherState;

    }
    public void DoStuff()
    {
        internalState = 42;
        anotherState = "i konw the question too";

    }

    public void PrintState()
    {
        System.Console.WriteLine("current state is{0}{1}", internalState, anotherState);
     }

}

posted on 2005-11-01 13:32  井泉  阅读(155)  评论(0编辑  收藏  举报

导航