核心
就是保存某个对象内部状态的拷贝,这样以后就可以将该对象恢复到原先的状态。
开发中常见的应用场景
/** * 备忘录类 * */ public class EmpMemento { private String ename; private int age; private double salary; public EmpMemento(Emp emp) { super(); this.ename = emp.getEname(); this.age = emp.getAge(); this.salary = emp.getSalary(); } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } } public class Emp { private String ename; private int age; private double salary; /*进行备忘操作,并返回备忘录对象*/ public EmpMemento memento(){ return new EmpMemento(this); } public void recovery(EmpMemento emt){ this.ename = emt.getEname(); this.age = emt.getAge(); this.salary = emt.getSalary(); } public Emp(String ename, int age, double salary) { super(); this.ename = ename; this.age = age; this.salary = salary; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } } /** * 负责人类 */ public class CareTaker { private EmpMemento empMemento; /*可以通过增加容器,设置多个备忘点*/ private List<EmpMemento> list = new ArrayList<EmpMemento>(); public EmpMemento getEmpMemento() { return empMemento; } public void setEmpMemento(EmpMemento empMemento) { this.empMemento = empMemento; } } public class Client { public static void main(String[] args) { CareTaker taker = new CareTaker(); Emp emp = new Emp("Somnus",25,10000.0); System.out.println("第一次打印的对象:"+emp.getEname()+"|"+emp.getAge()); taker.setEmpMemento(emp.memento()); emp.setEname("Smile"); emp.setAge(30); emp.setSalary(20000.0); System.out.println("第二次打印的对象:"+emp.getEname()+"|"+emp.getAge()); emp.recovery(taker.getEmpMemento()); System.out.println("第三次打印的对象:"+emp.getEname()+"|"+emp.getAge()); } }
JAVA设计模式(20):行为型-备忘录模式(Memento)
原文地址:http://blog.csdn.net/lovesomnus/article/details/45771683