核心:保存对象内部状态的拷贝,以便能恢复该对象。适用于回滚操作
结构:
源发器类Originator:被备忘保存的数据对象
备忘录类Memento:复杂拷贝Originator对象的内部状态
负责人类Caretake:管理备忘对象
备忘录模式模拟信息恢复:
Originator:
/*源发器类*/
public class Emp {
private String ename;//基本信息
private int age;
private double salary;
//set,get方法
public Emp(String ename,int age,double salary){
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 EmpMemento memento(){//进行备忘操作
return new EmpMemento(this);//返回一个备忘的对象
}
public void recovery(EmpMemento emp){//通过备忘对象进行当前对象恢复操作
this.setEname(emp.getEname());
this.setAge(emp.getAge());
this.setSalary(emp.getSalary());
}
}
备忘录类:
public class EmpMemento {
private String ename;
private int age;
private double salary;
public EmpMemento(Emp emp) {
this.ename = emp.getEname();
this.age = emp.getAge();
this.salary = emp.getSalary();
}
public String getEname() {
return ename;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
}
负责人类:
可以定义一个容器来进行备忘对象管理与返回
/*负责人类*/
public class CareTaker {
private EmpMemento empMemento;
public EmpMemento getEmpMemento() {
return empMemento;
}
public void setEmpMemento(EmpMemento emp) {
this.empMemento = emp;
}
}
客户端实现备忘录模式:
public class client {
public static void main(String[] args) {
CareTaker taker=new CareTaker();
Emp emp=new Emp("四毛",21,30000);
System.out.println("第一次输入emp信息"+emp.getEname()+emp.getAge());
taker.setEmpMemento(emp.memento());//将该信息设置备忘
emp.setEname("小杰航");
System.out.println("修改输入emp信息后"+emp.getEname()+emp.getAge());
emp.recovery(taker.getEmpMemento());//恢复备忘信息
System.out.println("恢复emp信息后"+emp.getEname()+emp.getAge());
}
}
当备忘点过多时,将备忘录压栈