支持回滚状态的一种模式。
核心:
创建一个拷贝对象进行备份。
给数据对象两个方法:1、进行备份。2、回滚。
需要备份的数据:
public class Datas { private int id; private String name; private double salary; //进行备份,获取备份对象 public DatasMemento memento(){ return new DatasMemento(this); } //回滚操作,指定回滚对象 public void recovery(DatasMemento dm){ this.id = dm.getId(); this.name = dm.getName(); this.salary = dm.getSalary(); } public Datas(int id, String name, double salary) { this.id = id; this.name = name; this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "Datas{" + "id=" + id + ", name='" + name + '\'' + ", salary=" + salary + '}'; } }
备份对象:把对象数据拷贝一次罢了。
public class DatasMemento { private int id; private String name; private double salary; //通过构造器直接备份对象 public DatasMemento(Datas datas) { this.id = datas.getId(); this.name = datas.getName(); this.salary = datas.getSalary(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } }
测试:
public class Client { public static void main(String[] args) { //创建一个对象 Datas d = new Datas(1,"二哥",998); //准备一个容器,存放备份对象 List<DatasMemento> list = new ArrayList<>(); //备份一次,并且丢入容器中 list.add(d.memento()); //更改数据,并备份一次 d.setSalary(1111); list.add(d.memento()); System.out.println(d); //回滚操作:到最开始的情况 d.recovery(list.get(0)); System.out.println(d); //回滚操作:到第一次修改后 d.recovery(list.get(1)); System.out.println(d); } }
测试结果:
标签:salary,name,备份,模式,public,备忘录,id,Memento,String From: https://www.cnblogs.com/lurenjia-bky/p/16929541.html