备忘录模式(Memento)
备忘录模式:在不破坏封装性的前提下,捕捉一个对象的内部状态,并在改对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
备忘录模式比较适合功能比较复杂的,但需要维护或记录属性历史的类。或者需要保存的属性只是众多属性中的一小部分时,Originator可以根据保存的Memento信息还原到前一状态。
public class Role { private int blood; //血量 private int mana; //蓝量 public int getBlood() { return blood; } public void setBlood(int blood) { this.blood = blood; } public int getMana() { return mana; } public void setMana(int mana) { this.mana = mana; } public Role(int blood, int mana) { this.blood = blood; this.mana = mana; } //之前的状态 public void before() { System.out.println("血量:"+getBlood()+"\t"+"蓝量:"+getMana()); }
public class Memento { private int blood; //血量 private int mana; //蓝量 public int getBlood() { return blood; } public void setBlood(int blood) { this.blood = blood; } public int getMana() { return mana; } public void setMana(int mana) { this.mana = mana; } public Memento(int blood, int mana) { this.blood = blood; this.mana = mana; } }
public class Caretaker { private Memento memento; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this.memento = memento; } }
public class MementoTest { public static void main(String[] args) { Role role=new Role(100,100); System.out.println("大战Boss之前"); role.before(); Caretaker caretaker=new Caretaker(); Memento memento=role.after(); caretaker.setMemento(memento); role.setBlood(20); role.setMana(10); System.out.println("大战Boss之后"); role.before(); } }
http://www.cnblogs.com/S2223/p/6053427.html