一、介绍
1)备忘录模式(Memento Pattern)在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态
2)可以这里理解备忘录模式:现实生活中的备忘录是用来记录某些要去做的事情,或者是记录已经达成的共同意见的事情,以防忘记了。而在软件层面,备忘录模式有着相同的含义,备忘录对象主要用来记录一个对象的某种状态,或者某些数据,当要做回退时,可以从备忘录对象里获取原来的数据进行恢复操作
3)备忘录模式属于行为型模式
二、实现
备忘录类
package com.swust.java.行为型模式.备忘录模式;
/**
* 备忘录类
*/
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;
}
}
源发器类
package com.swust.java.行为型模式.备忘录模式;
/**
* 源发器类
*/
public class Emp {
private String name;
private int age;
private double salary;
// 备忘操作,并返回备忘录对象
public EmpMemento memento(){
return new EmpMemento(this);
}
// 进行数据恢复 恢复成指定备忘录对象的值
public void recovery(EmpMemento em){
this.name = em.getName();
this.age = em.getAge();
this.salary = em.getSalary();
}
public Emp() {
}
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;
}
@Override
public String toString() {
return "Emp{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
负责人类
package com.swust.java.行为型模式.备忘录模式;
import java.util.List;
/**
* 负责人类
* 负责管理备忘录对象
*/
public class CareTaker {
private EmpMemento memento; // 只能保存一次状态
private List<EmpMemento> mementoList;// 通过容器存储多个备忘点
public EmpMemento getMemento() {
return memento;
}
public void setMemento(EmpMemento memento) {
this.memento = memento;
}
}
客户端类
package com.swust.java.行为型模式.备忘录模式;
public class Client {
public static void main(String[] args) {
CareTaker taker = new CareTaker();
Emp emp = new Emp("张三",18,3000);
System.out.println("第一次打印对象:"+emp);
// 设置备忘点
taker.setMemento(emp.memento());// 进行一次备份
// 修改源对象
emp.setAge(30);
emp.setName("李四");
emp.setSalary(4000);
System.out.println("第二次打印对象:"+emp);
emp.recovery(taker.getMemento()); // 恢复到备忘录对象保存的状态
System.out.println("第三次打印对象:"+emp);
}
}
执行结果
第一次打印对象:Emp{name='张三', age=18, salary=3000.0}
第二次打印对象:Emp{name='李四', age=30, salary=4000.0}
第三次打印对象:Emp{name='张三', age=18, salary=3000.0}