备忘录模式是一种软件设计模式:在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
发起者对象
public class Originator { private String name; private double sal; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSal() { return sal; } public void setSal(double sal) { this.sal = sal; } public MyMemento getMemento(){ return new MyMemento(this); } public void recover(MyMemento memento){ this.name = memento.getoName(); this.sal = memento.getoSal(); } }备忘录对象
public class MyMemento { private String oName; private double oSal; public MyMemento(Originator originator) { this.oName = originator.getName(); this.oSal = originator.getSal(); } public String getoName() { return oName; } public void setoName(String oName) { this.oName = oName; } public double getoSal() { return oSal; } public void setoSal(double oSal) { this.oSal = oSal; } }备忘录管理对象
public class CareTake { private MyMemento memento; public MyMemento getMemento() { return memento; } public void setMemento(MyMemento memento) { this.memento = memento; } }测试类
public class MyMementoTest { public static void main(String[] args) { CareTake careTake = new CareTake(); Originator originator = new Originator(); originator.setName("小明"); originator.setSal(10000); System.out.println(originator.getName()+"的薪资为:"+originator.getSal()); MyMemento memento = originator.getMemento(); careTake.setMemento(memento); originator.setSal(20000); System.out.println(originator.getName()+"涨薪之后的薪资为:"+originator.getSal()); originator.recover(careTake.getMemento()); System.out.println(originator.getName()+"原来的薪资为:"+originator.getSal()); } }