一、备忘录模式概述

  保存某个对象内部状态的拷贝,使得以后就可以将该对象恢复到原先的状态。

  结构:

    (1)源发器类 Originator

        负责创建一个备忘录 Memento,用以记录当前时刻它的内部状态,并可使用备忘录恢复内部状态。

    (2)备忘录类 Memento

        负责存储 Originator 对象的内部状态,并可防止 Originator 以外的其他对象访问备忘录 Memento 。

    (3)负责人类 CareTake

        负责保存备忘录 Memento 。

二、备忘录模式示例代码

 /**
* 备忘录类
* @author CL
*
*/
public class EmpMemento {
private String name;
private int age;
private double salary; public EmpMemento(Employee emp) {
this.name = emp.getName();
this.age = emp.getAge();
this.salary = emp.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;
} }
 /**
* 源发器类
* @author CL
*
*/
public class Employee {
private String name;
private int age;
private double salary; public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
} /**
* 进行备忘操作,并返回备忘录对象
* @return
*/
public EmpMemento memento() {
return new EmpMemento(this);
} /**
* 进行数据恢复,恢复成指定备忘录对象的值
*/
public void recovery(EmpMemento emt) {
this.name = emt.getName();
this.age = emt.getAge();
this.salary = emt.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;
} }
 /**
* 负责人类
* @author CL
*
*/
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;
} }

  测试:

 /**
* 测试备忘录模式
* @author CL
*
*/
public class Client { public static void main(String[] args) {
CareTaker ct = new CareTaker(); Employee emp = new Employee("曹磊", 23, 8000);
System.out.println("第一次打印对象:"+emp.getName()+"---"+emp.getAge()
+"---"+emp.getSalary()); //备忘一次
ct.setMemento(emp.memento()); //修改源发器类的值
emp.setName("Tom");
emp.setAge(99);
emp.setSalary(123456); System.out.println("第二次打印对象:"+emp.getName()+"---"+emp.getAge()
+"---"+emp.getSalary()); //恢复到备忘录对象保存的状态
emp.recovery(ct.getMemento()); System.out.println("第三次打印对象:"+emp.getName()+"---"+emp.getAge()
+"---"+emp.getSalary()); }
}

  控制台输出:

第一次打印对象:曹磊---23---8000.0
第二次打印对象:Tom---99---123456.0
第三次打印对象:曹磊---23---8000.0

  注意:本例子中只设置了一个备忘点,当通过容器设置多个备忘点时,就可以实现 Word 中 Ctrl + Z 和 Ctrl + Y 的操作。

三、备忘录模式常见开发应用场景

  (1)棋类游戏中的悔棋操作;

  (2)Office 中的撤销、恢复功能;

  (3)数据库软件中事务管理的回滚操作;

  (4)Photoshop 软件中的历史记录;

  (5)…………

05-15 01:03