来源:http://www.bjsxt.com/
一、【GOF23设计模式】_备忘录模式、多点备忘、事务操作、回滚数据底层架构
package com.test.memento;
/**
* 源发器类
*/
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;
}
}
package com.test.memento;
/**
* 备忘录类
*/
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;
}
}
package com.test.memento; import java.util.ArrayList; /**
* 负责人类
*/
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;
}
}
package com.test.memento; public class Client {
public static void main(String[] args) {
CareTaker careTaker = new CareTaker(); Emp emp = new Emp("小高", 18, 900);
System.out.println("第一次打印对象:"+emp.getEname()+"--"
+emp.getAge()+"--"+emp.getSalary()); careTaker.setMemento(emp.memento());//备忘一次 emp.setAge(38);
emp.setEname("小搞");
emp.setSalary(9000); System.out.println("第二次打印对象:"+emp.getEname()+"--"
+emp.getAge()+"--"+emp.getSalary()); emp.recovery(careTaker.getMemento());//恢复到备忘录对象保存的状态 System.out.println("第三次打印对象:"+emp.getEname()+"--"
+emp.getAge()+"--"+emp.getSalary());
}
}
控制台输出:
第一次打印对象:小高--18--900.0
第二次打印对象:小搞--38--9000.0
第三次打印对象:小高--18--900.0