备忘录模式

1、场景

1、棋类游戏中的,悔棋
2、 普通软件中的,撤销操作
3、 数据库软件中的,事务管理中的,回滚操作
4、 Photoshop软件中的,历史记录

2、核心

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

3、结构

  • 源发器类 Originator
  • 备忘录类 Memento
  • 负责人类 CareTaker
    在这里插入图片描述

4、代码实现

4.1、源发器类
/**
 * 源发器类
 */
public class Emp {
    private String name;
    private int age;
    private double salary;

    //进行备忘操作,并返回备忘录对象
    public EmpMemento memento(){
        return new EmpMemento(this);
    }
    //进行数据恢复,恢复成制定备忘录对象的值
    public void recovery(EmpMemento memento){
        this.name = memento.getName();
        this.age = memento.getAge();
        this.salary = memento.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;
    }
    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}
4.2、备忘录类
/**
 * 备忘录类
 */
public class EmpMemento {
    private String name;
    private int age;
    private double salary;

    public EmpMemento(Emp 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;
    }
}

4.3、负责人类
/**
 * 负责人类
 * 负责管理备忘录对象
 */
public class CareTaker {
    private EmpMemento empMemento;
//    private List<EmpMemento> list = new ArrayList<>();
    public EmpMemento getEmpMemento() {
        return empMemento;
    }
    public void setEmpMemento(EmpMemento empMemento) {
        this.empMemento = empMemento;
    }
}
4.4、测试结果

在这里插入图片描述

5、负责人类注意点

在负责人类负责保存好的备忘录对象。可以通过增加容器,设置多个“备忘点”

private List<EmpMemento> list = new ArrayList<>();

备忘点较多时:

  • 可以将备忘点压栈
public class CareTaker {

		private Memento memento;
		
		private Stack<Memento> stack = new Stack<Memento>();
	}
  • 将多个备忘录对象,序列化和持久化

6、代码UML图

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值