設計模式之備忘錄模式
阿新 • • 發佈:2017-09-05
set 2017年 image 對象 array mem .com void oid
代碼實現
/** * 源發器類 * @author bzhx * 2017年3月15日 */ public class Emp { private String ename; private int age; private double salary; //備忘操作,並返回備忘錄對象 public EmpMemento memento(){ return new EmpMemento(this); } //進行數據恢復,恢復成指定備忘錄對象的值 public void源發器類recovery(EmpMemento mmt){ this.ename = mmt.getEname(); this.age = mmt.getAge(); this.salary = mmt.getSalary(); } public Emp(String ename, int age, double 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 double getSalary() { return salary; }public void setSalary(double salary) { this.salary = salary; } }
/** * 備忘錄類 * @author bzhx * 2017年3月15日 */ public class EmpMemento { private String ename; private int age; private double salary; public EmpMemento(Emp 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 double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } }備忘錄類
/** * 負責人類 * 負責管理備忘錄對象 * @author bzhx * 2017年3月15日 */ 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; } }負責人類
public class Client { public static void main(String[] args) { CareTaker taker = new CareTaker(); Emp emp = new Emp("高琪",18,900); System.out.println("第一次打印對象:" + emp.getEname() + "----" + emp.getAge()+"----"+emp.getSalary()); taker.setMemento(emp.memento()); //備忘一次 emp.setAge(38); emp.setEname("馬奇"); emp.setSalary(8888); System.out.println("第二次打印對象:" + emp.getEname() + "----" + emp.getAge()+"----"+emp.getSalary()); emp.recovery(taker.getMemento()); //恢復到備忘錄對象保存的狀態 System.out.println("第三次打印對象:" + emp.getEname() + "----" + emp.getAge()+"----"+emp.getSalary()); } }測試
第一次打印對象:高琪----18----900.0 第二次打印對象:馬奇----38----8888.0 第三次打印對象:高琪----18----900.0結果
設計模式之備忘錄模式