备忘录模式的核心:
就是保存某个对象内部状态的拷贝,这样以后就可以将该对象恢复到原先的状态。
备忘录模式的结构:
1.源发器类Originator:负责创建一个备忘录Memento,用以记录当前时刻它的内部状态,并可以使用备忘录恢复内部状态;
2.备忘录类Memento:负责存储Originator对象的内部状态,并可以防止Originator以外的其他对象访问备忘录Memento;
3.负责人类CareTake:负责保存好备忘录Memento;
下面用代码说明:
1.创建源发器类:
/**
* 源发器类
* @author Administrator
*
*/
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;
}
}
2.创建备忘录类:
/**
* 备忘录类
* @author Administrator
*
*/
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;
}
}
3.创建负责人类:
/**
* 负责人类
* 负责管理备忘录对象
* @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;
}
}
4.客户端测试:
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());
}
}
备忘录模式在开发中应用场景:
1.普通软件中的撤销操作;
2.数据库事务管理中的回滚;