标签:c style class blog code java
备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
简单描述:一个Memento类,代表Originator中要备份的属性。Originator负责生成备份和还原备份,CareTaker负责存储备份
大话设计模式中的截图:
例子代码:
Memento类:
1 package com.longsheng.memento; 2 3 public class Memento { 4 5 private String stateA; 6 private String stateB; 7 private String stateC; 8 9 public Memento(String stateA, String stateB, String stateC) { 10 this.stateA = stateA; 11 this.stateB = stateB; 12 this.stateC = stateC; 13 } 14 15 public String getStateA() { 16 return stateA; 17 } 18 19 public String getStateB() { 20 return stateB; 21 } 22 23 public String getStateC() { 24 return stateC; 25 } 26 27 28 }
Originator类:
1 package com.longsheng.memento; 2 3 public class Originator { 4 5 private String stateA; 6 private String stateB; 7 private String stateC; 8 9 public void initOriginator() { 10 stateA = "startA"; 11 stateB = "startB"; 12 stateC = "startC"; 13 } 14 15 public void changeOriginator() { 16 stateA = "endA"; 17 stateB = "endB"; 18 stateC = "endC"; 19 } 20 21 public void show() { 22 System.out.println("Originator--" + "stateA=" + stateA + ",stateB=" 23 + stateB + ",stateC=" + stateC); 24 } 25 26 public Memento createMemento() { 27 return new Memento(stateA, stateB, stateC); 28 } 29 30 public void recoveryState(Memento mMemento) { 31 this.stateA = mMemento.getStateA(); 32 this.stateB = mMemento.getStateB(); 33 this.stateC = mMemento.getStateC(); 34 } 35 36 }
CareTaker类:
1 package com.longsheng.memento; 2 3 public class CareTaker { 4 5 private Memento mMemento = null; 6 7 public Memento getmMemento() { 8 return mMemento; 9 } 10 11 public void setmMemento(Memento mMemento) { 12 this.mMemento = mMemento; 13 } 14 15 16 17 }
客户端:
1 package com.longsheng.memento; 2 3 public class Client { 4 5 public static void main(String[] args) { 6 Originator mOriginator = new Originator(); 7 CareTaker mCareTaker = new CareTaker(); 8 //初始状态 9 mOriginator.initOriginator(); 10 mOriginator.show(); 11 mCareTaker.setmMemento(mOriginator.createMemento()); 12 //更改状态 13 mOriginator.changeOriginator(); 14 mOriginator.show(); 15 //恢复状态 16 mOriginator.recoveryState(mCareTaker.getmMemento()); 17 mOriginator.show(); 18 } 19 20 }
运行结果:
1 Originator--stateA=startA,stateB=startB,stateC=startC 2 Originator--stateA=endA,stateB=endB,stateC=endC 3 Originator--stateA=startA,stateB=startB,stateC=startC
备忘录模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性中的一小部分时,Originator可以根据保存的Memento信息还原到前一状态。
其中管着类CareTaker只是负责存储数据,控制客户端不能对Memento的细节进行访问
大话设计模式_备忘录模式(Java代码),布布扣,bubuko.com
标签:c style class blog code java
原文地址:http://www.cnblogs.com/creasylai19/p/3776074.html