备忘录模式
一、概述
- 就是保存某个对象内部状态的拷贝,这样以后就可以将该对象恢复到 原先的状态。
- 结构
- 源发器类Originator
- 备忘录类Memento
- 负责人类CareTaker
- 开发中常见的场景
- 棋类游戏中的,悔棋
- 普通软件中的,撤销操作
- 数据库软件中的,事务管理中的,回滚操作
- Photoshop软件中的,历史记录
二、代码实现
-
源发器类
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; } }
-
备忘录类
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; } }
-
负责人类
/** * 负责人类 * 负责管理备忘录对象 * @author Administrator * */ public class CareTaker { private EmpMemento memento; // 备忘多个状态 // private List<EmpMemento> list = new ArrayList<EmpMemento>(); public EmpMemento getMemento() { return memento; } public void setMemento(EmpMemento memento) { this.memento = 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()); } }
三、类图
ps:备忘点较多时,可以将备忘录压栈,也可以将备忘录对象序列和持久化。
public class CareTaker {
private Memento memento;
private Stack<Memento> stack = new Stack<Memento>();
}