首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

举动型模式-备忘录模式(Memento)

2013-08-06 
行为型模式--备忘录模式(Memento)Original类是原始类,里面有需要保存的属性value及创建一个备忘录类,用来

行为型模式--备忘录模式(Memento)

Original类是原始类,里面有需要保存的属性value及创建一个备忘录类,用来保存value值。Memento类是备忘录类,Storage类是存储备忘录的类,持有Memento类的实例,该模式很好理解。直接看源码:

[java]?view plaincopy
  1. public?class?Original?{??
  2. ??????
  3. ????private?String?value;??
  4. ??????
  5. ????public?String?getValue()?{??
  6. ????????return?value;??
  7. ????}??
  8. ??
  9. ????public?void?setValue(String?value)?{??
  10. ????????this.value?=?value;??
  11. ????}??
  12. ??
  13. ????public?Original(String?value)?{??
  14. ????????this.value?=?value;??
  15. ????}??
  16. ??
  17. ????public?Memento?createMemento(){??
  18. ????????return?new?Memento(value);??
  19. ????}??
  20. ??????
  21. ????public?void?restoreMemento(Memento?memento){??
  22. ????????this.value?=?memento.getValue();??
  23. ????}??
  24. }??
[java]?view plaincopy
  1. public?class?Memento?{??
  2. ??????
  3. ????private?String?value;??
  4. ??
  5. ????public?Memento(String?value)?{??
  6. ????????this.value?=?value;??
  7. ????}??
  8. ??
  9. ????public?String?getValue()?{??
  10. ????????return?value;??
  11. ????}??
  12. ??
  13. ????public?void?setValue(String?value)?{??
  14. ????????this.value?=?value;??
  15. ????}??
  16. }??
[java]?view plaincopy
  1. public?class?Storage?{??
  2. ??????
  3. ????private?Memento?memento;??
  4. ??????
  5. ????public?Storage(Memento?memento)?{??
  6. ????????this.memento?=?memento;??
  7. ????}??
  8. ??
  9. ????public?Memento?getMemento()?{??
  10. ????????return?memento;??
  11. ????}??
  12. ??
  13. ????public?void?setMemento(Memento?memento)?{??
  14. ????????this.memento?=?memento;??
  15. ????}??
  16. }??

测试类:

[java]?view plaincopy
  1. public?class?Test?{??
  2. ??
  3. ????public?static?void?main(String[]?args)?{??
  4. ??????????
  5. ????????//?创建原始类??
  6. ????????Original?origi?=?new?Original("egg");??
  7. ??
  8. ????????//?创建备忘录??
  9. ????????Storage?storage?=?new?Storage(origi.createMemento());??
  10. ??
  11. ????????//?修改原始类的状态??
  12. ????????System.out.println("初始化状态为:"?+?origi.getValue());??
  13. ????????origi.setValue("niu");??
  14. ????????System.out.println("修改后的状态为:"?+?origi.getValue());??
  15. ??
  16. ????????//?回复原始类的状态??
  17. ????????origi.restoreMemento(storage.getMemento());??
  18. ????????System.out.println("恢复后的状态为:"?+?origi.getValue());??
  19. ????}??
  20. }??

输出:

初始化状态为:egg
修改后的状态为:niu
恢复后的状态为:egg

简单描述下:新建原始类时,value被初始化为egg,后经过修改,将value的值置为niu,最后倒数第二行进行恢复状态,结果成功恢复了。其实我觉得这个模式叫“备份-恢复”模式最形象。

热点排行