JAVA设计模式(20):行为型-备忘录模式(Memento)
时间:2015-05-16 23:26:32
收藏:0
阅读:370
场景
结构
- 录入大批人员资料。正在录入当前人资料时,发现上一个人录错了,此时需要恢复上一个人的资料,再进行修改。
- word文档编辑时,忽然电脑死机或断电,再打开时,可以看到word提示恢复到以前的文档。
- 管理系统中,公文撤回功能。公文发出去后,想撤回来。
核心
就是保存某个对象内部状态的拷贝,这样以后就可以将该对象恢复到原先的状态。结构
- 源发器类Originator
- 备忘录类Memento
- 负责人类CateTaker
开发中常见的应用场景
- 棋类游戏中的,悔棋
- 普通软件中的,撤销操作
- 数据库软件中的,事务管理中的,回滚操作
- photoshop软件中的,历史记录
/** * 备忘录类 * */ 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()); } }
评论(0)