首页 > 代码库 > 备忘录模式——HeadFirst设计模式学习笔记

备忘录模式——HeadFirst设计模式学习笔记

备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。可以将该对象恢复到原先保存的状态

Java中可以使用序列化机制保存状态

技术分享

  • 发起人:记录当前时刻的内部状态,负责定义哪些属于备份范围的状态,负责创建和恢复备忘录数据。
  • 备忘录:负责存储发起人对象的内部状态,在需要的时候提供发起人需要的内部状态。
  • 管理角色:对备忘录进行管理,保存和提供备忘录。

 

特点:

  • 被存储的状态放在外面,不和关键对象放在一起
  • 保持了关键对象的封装,提供实现恢复的能力

 

缺点:

  • 资源与时间的消耗

 

举例:

通过备忘录管理游戏角色信息

 游戏角色类:

 1 public class PlayRole {
 2     private int vitality;
 3     private int aggressivity;
 4     private int defencivity;
 5     public PlayRole(int vitality, int aggressivity, int defencivity) {
 6         super();
 7         this.vitality = vitality;
 8         this.aggressivity = aggressivity;
 9         this.defencivity = defencivity;
10     }
11     public PlayRole() {}
12     public RoleMemento createMemento() {
13         RoleMemento memento = new RoleMemento();
14         memento.setAggressivity(aggressivity);
15         memento.setDefencivity(defencivity);
16         memento.setVitality(vitality);
17         return memento;
18     }
19     public void setMemento(RoleMemento memento) {
20         this.aggressivity = memento.getAggressivity();
21         this.defencivity = memento.getDefencivity();
22         this.vitality = memento.getVitality();
23     }
24     public void showState() {
25         System.out.println("攻击力:" + this.aggressivity + "|防御力:" + this.defencivity + "|生命力:" + this.vitality);
26     }
27 ...//其他
28 }

备忘录类:

 1 public class RoleMemento {
 2     private int vitality;
 3     private int aggressivity;
 4     private int defencivity;
 5     public int getVitality() {
 6         return vitality;
 7     }
 8     public void setVitality(int vitality) {
 9         this.vitality = vitality;
10     }
11     public int getAggressivity() {
12         return aggressivity;
13     }
14     public void setAggressivity(int aggressivity) {
15         this.aggressivity = aggressivity;
16     }
17     public int getDefencivity() {
18         return defencivity;
19     }
20     public void setDefencivity(int defencivity) {
21         this.defencivity = defencivity;
22     }
23 }        

备忘录管理者,通过HashMap管理一个用户多个历史状态:

1 public class Caretaker {
2     Map<String, RoleMemento> mementoMap = new HashMap<>();
3     public RoleMemento getMemento(String index) {
4         return mementoMap.get(index);
5     }
6     public void setMemento(String index, RoleMemento memento) {
7         mementoMap.put(index, memento);
8     }
9 }

 

备忘录模式——HeadFirst设计模式学习笔记