记忆点(Memento)

类别:.NET开发 点击:0 评论:0 推荐:

 

很多情况下在我们改变了很多东西的时候。却开始后悔了。也许这就是人类的软弱一面。不管怎么样人生是无法回到原点的。可是软体可以,因为一切运行的程序都是加载在内存中的。所以即使改变了,我们也是可以有办法回到原点的。我想你也许已经猜到我要说什么了吧?是的。Memento 模式。一个很简单的模式。
//原对象
public class Originator {

  public int number;
  public object myObject = null;
         private Memento myMemobject;
  public Originator(){}
        
          public Memento MemObject{
             get{
                   return new Memento(this);
                  }
             set{
                    myMemobject=value;
                    this.number=myMemobject.Number;
                    this.myObject=myMemobject.O;
                  }
             }
  }

//记忆点
[Serializable]
private class Memento : ISerializable {

  private int Number;

  private Object O = null;

  public Memento( Originator o){

    number = o.number;
    O = o.myObject;

  }

}

//调用实例
public class Client
    {
        public static int Main(string[] args)
        {     
   Originator o = new Originator();
                                 Memento  m=o.MemObject;
                                                 //改变值
                                                 o.number=100;
                                                 o.myObject="object";
                                                 //还原
                                                o.MemObject=m;
                                                return 0;
        }
    }

Memento中保存了Originator中的number和object的值. 通过调用Originator中number和object值改变的话,通过调用属性方法可以恢复.这样就满足了面向对象的原则.

本文地址:http://com.8s8s.com/it/it45510.htm