备忘录模式就是保存某个对象内部状态的拷贝,这样就可以将对象回复到原先的状态。常见应用场景:数据库事务的回滚操作。
备忘类
public class Emp {
private String name;
private int age;
private double salary;
//进行备忘操作,返回备忘对象
public ConcreteEmp memento(){
return new ConcreteEmp(this);
}
//进行数据恢复
public void recover(ConcreteEmp emp){
this.age = emp.getAge();
this.name = emp.getName();
this.salary = emp.getSalary();
}
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 class CareTaker {
private ConcreteEmp emp;
public ConcreteEmp getEmp() {
return emp;
}
public void setEmp(ConcreteEmp emp) {
this.emp = emp;
}
}
维护状态的具体类
public class ConcreteEmp {
private String name;
private int age;
private double salary;
public ConcreteEmp(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;
}
}
测试类
public class Test {
public static void main(String[] args) {
CareTaker careTaker = new CareTaker();
Emp emp = new Emp("张三",21,6000);
System.out.println("第一次创建的对象:" + emp.getName() + "--" + emp.getAge() + "--" + emp.getSalary());
//备份一次
careTaker.setEmp(emp.memento());
//更改对象
emp.setAge(23);
emp.setName("李四");
emp.setSalary(7000);
System.out.println("第二次创建的对象:" + emp.getName() + "--" + emp.getAge() + "--" + emp.getSalary());
//恢复对象
emp.recover(careTaker.getEmp());
System.out.println("第三次创建的对象:" + emp.getName() + "--" + emp.getAge() + "--" + emp.getSalary());
}
}
最后的输出结果:
第一次创建的对象:张三–21–6000.0
第二次创建的对象:李四–23–7000.0
第三次创建的对象:张三–21–6000.0