标签:
来源:http://www.bjsxt.com/
一、【GOF23设计模式】_备忘录模式、多点备忘、事务操作、回滚数据底层架构
1 package com.test.memento; 2 /** 3 * 源发器类 4 */ 5 public class Emp { 6 private String ename; 7 private int age; 8 private double salary; 9 10 //进行备忘操作,并返回备忘录对象 11 public EmpMemento memento(){ 12 return new EmpMemento(this); 13 } 14 15 //进行数据恢复,恢复成制定备忘录对象的值 16 public void recovery(EmpMemento mmt){ 17 this.ename = mmt.getEname(); 18 this.age = mmt.getAge(); 19 this.salary = mmt.getSalary(); 20 } 21 public Emp(String ename, int age, double salary) { 22 super(); 23 this.ename = ename; 24 this.age = age; 25 this.salary = salary; 26 } 27 public String getEname() { 28 return ename; 29 } 30 public void setEname(String ename) { 31 this.ename = ename; 32 } 33 public int getAge() { 34 return age; 35 } 36 public void setAge(int age) { 37 this.age = age; 38 } 39 public double getSalary() { 40 return salary; 41 } 42 public void setSalary(double salary) { 43 this.salary = salary; 44 } 45 }
1 package com.test.memento; 2 /** 3 * 备忘录类 4 */ 5 public class EmpMemento { 6 private String ename; 7 private int age; 8 private double salary; 9 10 public EmpMemento(Emp e){ 11 this.ename = e.getEname(); 12 this.age = e.getAge(); 13 this.salary = e.getSalary(); 14 } 15 16 public String getEname() { 17 return ename; 18 } 19 public void setEname(String ename) { 20 this.ename = ename; 21 } 22 public int getAge() { 23 return age; 24 } 25 public void setAge(int age) { 26 this.age = age; 27 } 28 public double getSalary() { 29 return salary; 30 } 31 public void setSalary(double salary) { 32 this.salary = salary; 33 } 34 }
1 package com.test.memento; 2 3 import java.util.ArrayList; 4 5 /** 6 * 负责人类 7 */ 8 public class CareTaker { 9 private EmpMemento memento; 10 11 // private List<EmpMemento> list = new ArrayList<EmpMemento>(); 12 13 public EmpMemento getMemento() { 14 return memento; 15 } 16 17 public void setMemento(EmpMemento memento) { 18 this.memento = memento; 19 } 20 }
1 package com.test.memento; 2 3 public class Client { 4 public static void main(String[] args) { 5 CareTaker careTaker = new CareTaker(); 6 7 Emp emp = new Emp("小高", 18, 900); 8 System.out.println("第一次打印对象:"+emp.getEname()+"--" 9 +emp.getAge()+"--"+emp.getSalary()); 10 11 careTaker.setMemento(emp.memento());//备忘一次 12 13 emp.setAge(38); 14 emp.setEname("小搞"); 15 emp.setSalary(9000); 16 17 System.out.println("第二次打印对象:"+emp.getEname()+"--" 18 +emp.getAge()+"--"+emp.getSalary()); 19 20 emp.recovery(careTaker.getMemento());//恢复到备忘录对象保存的状态 21 22 System.out.println("第三次打印对象:"+emp.getEname()+"--" 23 +emp.getAge()+"--"+emp.getSalary()); 24 } 25 }
控制台输出: 第一次打印对象:小高--18--900.0 第二次打印对象:小搞--38--9000.0 第三次打印对象:小高--18--900.0
标签:
原文地址:http://www.cnblogs.com/erbing/p/5802690.html