备忘录模式(memento)
备忘录模式的核心:
就是保存某个对象内部状态的拷贝,这样以后就可以将该对象恢复到原先的状态。
备忘录模式的结构:
源发器类Originator:负责创建一个备忘录Memento,用以记录当前时刻它的内部状态,并可以使用备忘录恢复内部状态;
备忘录类Memento:负责存储Originator对象的内部状态,并可以防止Originator以外的其他对象访问备忘录Memento;
负责人类CareTake:负责保存好备忘录Memento;
下面用代码说明:
创建源发器类:
package com.note.pattern.memento; /** * 源发器类 */ public class Emp { private String ename; private int age; private double salary; // 进行备忘操作,并返回备忘录对象 public EmpMemento memento() { return new EmpMemento(this); } // 进行数据恢复,恢复成指定备忘录对象的值 public void recovery(EmpMemento mmt) { this.ename = mmt.getEname(); this.age = mmt.getAge(); this.salary = mmt.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; } }
创建备忘录类:
package com.note.pattern.memento; /** * * 备忘录类 */ public class EmpMemento { private String ename; private int age; private double salary; public EmpMemento(Emp e) { this.ename = e.getEname(); this.age = e.getAge(); this.salary = e.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; } }
创建负责人类
package com.note.pattern.memento; /** * 负责人类 负责管理备忘录对象 */ public class CareTaker { // private List<EmpMemento> list = new ArrayList<EmpMemento>(); private EmpMemento memento; public EmpMemento getMemento() { return memento; } public void setMemento(EmpMemento memento) { this.memento = memento; } }
客户端测试:
package com.note.pattern.memento; public class Client { public static void main(String[] args) { CareTaker taker = new CareTaker(); Emp emp = new Emp("高淇", 18, 900); System.out.println("第一次打印对象:" + emp.getEname() + "---" + emp.getAge() + "---" + emp.getSalary()); taker.setMemento(emp.memento()); // 备忘一次 emp.setAge(38); emp.setEname("搞起"); emp.setSalary(9000); System.out.println("第二次打印对象:" + emp.getEname() + "---" + emp.getAge() + "---" + emp.getSalary()); emp.recovery(taker.getMemento()); // 恢复到备忘录对象保存的状态 System.out.println("第三次打印对象:" + emp.getEname() + "---" + emp.getAge() + "---" + emp.getSalary()); } }
运行结果
第一次打印对象:高淇---18---900.0 第二次打印对象:搞起---38---9000.0 第三次打印对象:高淇---18---900.0
备忘录模式在开发中应用场景:
普通软件中的撤销操作;
数据库事务管理中的回滚;