一系列的操作之后恢复原来的状态。实际的使用场景有事务的回滚操作等。
在备忘录模式中有以下的几种对象: 2.1源发器:Originator 2.2备忘录类:Memento 2.3负责人CareTake 具体的UML示意图如下:
首先定义Emp类:
public class Emp { private String name; private int age; private double salary; public Emp(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } 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 EmpMemento memento(){ return new EmpMemento(this); } //进行数据恢复,恢复成备忘录对象的值 public void recovery(EmpMemento emto){ this.name=emto.getName(); this.age=emto.getAge(); this.salary=emto.getSalary(); } }定义EmpMemento类:
public class EmpMemento { private String name; private int age; private double salary; public EmpMemento(Emp e) {//这是关键 this.name=e.getName(); this.age=e.getAge(); this.salary=e.getSalary(); } public String getName() { return name; } public void setName(String name) { this.name = name; } 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; } }
编写CareTaker类:
public class CareTaker { private EmpMemento memento; public EmpMemento getMemento() { return memento; } public void setMemento(EmpMemento memento) { this.memento = memento; } }
最后给出测试类:
public class Client { public static void main(String[] args) { CareTaker careTaker=new CareTaker(); Emp emp=new Emp("小强",90,900); System.out.println(emp.getName()+" "+emp.getAge()+" "+emp.getSalary()); careTaker.setMemento(emp.memento()); emp.setAge(9); System.out.println(emp.getName()+" "+emp.getAge()+" "+emp.getSalary()); emp.recovery(careTaker.getMemento()); System.out.println(emp.getName()+" "+emp.getAge()+" "+emp.getSalary()); } }
备忘录模式保存了内部状态的拷贝,以后直接恢复即可。 代码地址:https://github.com/memoryexplosion/design_pattern_review/tree/master/src/java/memeto
