标签:mes 对象 car name 备忘录 模式 mpm 应用 out
备忘录模式就是保存某个对象内部状态的拷贝,这样就可以将该对象恢复为原来的对象。
结构:
源发器类;备忘录类;负责人类;
//源发器类
public class Emo { private String ename; private int age; private String salary; //进行备忘录操作 public EmpMemento memento(){ return new EmpMemento(this); } //进行数据恢复 public void recovery(EmpMemento em){ this.ename = em.getEname(); this.age = em.getAge(); this.salary = em.getSalary(); } public Emo(String ename, int age, String salary) { super(); this.ename = ename; this.age = age; this.salary = salary; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } }
//备忘录类 public class EmpMemento { private String ename; private int age; private String salary; public EmpMemento(Emo e){ this.ename = e.getEname(); this.age = e.getAge(); this.salary = e.getSalary(); } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } }
//负责人类 public class CareTake { private EmpMemento empMemento;//可以将其保存到容器中 比如Stack public EmpMemento getEmpMemento() { return empMemento; } public void setEmpMemento(EmpMemento empMemento) { this.empMemento = empMemento; } } public class Client { public static void main(String[] args) { CareTake careTake = new CareTake(); Emo emo = new Emo("kobe", 23, "15000"); System.out.println("第一次打印:"+emo.getEname()+" "+emo.getAge()+" "+emo.getSalary()); careTake.setEmpMemento(emo.memento()); emo.setEname("james"); emo.setAge(33); emo.setSalary("15000"); System.out.println("第二次打印:"+emo.getEname()+" "+emo.getAge()+" "+emo.getSalary()); emo.recovery(careTake.getEmpMemento()); System.out.println("第三次打印:"+emo.getEname()+" "+emo.getAge()+" "+emo.getSalary()); } } 运行结果: 第一次打印:kobe 23 15000 第二次打印:james 33 18000 第三次打印:kobe 23 15000
应用场景:
棋类游戏中:悔棋
普通软件中:撤销操作
数据库软件中:回滚操作
标签:mes 对象 car name 备忘录 模式 mpm 应用 out
原文地址:https://www.cnblogs.com/menbo/p/10193011.html