备忘录模式(Memento)定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便以后当需要时能将该对象恢复到原先保存的状态。该模式又叫快照模式。

备忘录模式的优点有:

1、提供了一种可以恢复状态的机制。当用户需要时能够比较方便地将数据恢复到某个历史的状态。

2、实现了内部状态的封装。除了创建它的发起人之外,其他对象都不能够访问这些状态信息。

3、简化了发起人类。发起人不需要管理和保存其内部状态的各个备份,所有状态信息都保存在备忘录中,并由管理者进行管理,这符合单一职责原则。

 

创始人类:

 1 //记录当前时刻的内部状态信息BLL
 2 public class Originator {
 3 
 4     private String state;
 5 
 6     public void setState(String state) {
 7         this.state = state;
 8     }
 9 
10     public String getState() {
11         return state;
12     }
13 
14     // 使用当前状态创建副本
15     public Memento createMemento() {
16         return new Memento(state);
17     }
18 
19     // 从副本中恢复状态
20     public void restoreMemento(Memento m) {
21         this.setState(m.getState());
22     }
23 }

 

备忘录类:

 1 //状态对象Model
 2 public class Memento {
 3     private String state; 
 4     public Memento(String state)
 5     { 
 6         this.state=state; 
 7     }     
 8     public void setState(String state)
 9     { 
10         this.state=state; 
11     }
12     public String getState()
13     { 
14         return state; 
15     }
16 }

 

管理员类:

 1 //状态集
 2 public class Caretaker {
 3     private Stack<Memento> mementos;
 4 
 5     public Caretaker() {
 6         if (mementos == null) {
 7             mementos = new Stack<Memento>();
 8         }
 9     }
10 
11     public void Push(Memento m) {
12         mementos.add(m);
13     }
14 
15     public Memento Pop() {
16         if (mementos != null && !mementos.empty()) {
17             return mementos.pop();
18         } else {
19             return null;
20         }
21     }
22 }

 

调用方式:

 1 public class Client {
 2     public static void main(String[] args) {
 3         Originator or = new Originator();
 4 
 5         or.setState("S0");
 6         System.out.println("初始状态:" + or.getState());
 7 
 8         Caretaker cr = new Caretaker();
 9         Memento memento1 = or.createMemento();// 保存状态
10         cr.Push(memento1); // SAVE
11 
12         or.setState("S1");
13         System.out.println("新的状态:" + or.getState());
14 
15         Memento memento2 = cr.Pop();// 恢复状态
16         or.restoreMemento(memento2);// LOAD
17         System.out.println("恢复状态:" + or.getState());
18     }
19 }

执行结果:

 

posted on 2019-12-28 11:19  Sempron2800+  阅读(145)  评论(0编辑  收藏  举报