文章出處

索引

別名

  • Token

意圖

在不破壞封裝性的前提下,捕獲一個對象的內部狀態,并在該對象之外保存這個狀態。這樣以后就可將該對象恢復到原先保存的狀態。

Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

結構

參與者

Memento

  • Memento 存儲 Originator 對象的內部狀態。Originator 根據需要決定 Memento 存儲那些內部狀態。
  • 防止 Originator 以外的其他對象訪問 Memento。Memento 可實現兩個接口,Caretaker 只能看到 Memento 的窄接口,Originator 可以看到寬接口。

Originator

  • Originator 創建一個 Memento,用以記錄當前時刻的內部狀態。
  • 使用 Memento 恢復內部狀態。

Caretaker

  • 負責保存 Memento。
  • 不能對 Memento 的內容進行操作和檢查。

適用性

在以下情況下可以使用 Memento 模式:

  • 必須保存一個對象在某一個時刻的狀態,這樣以后需要時它才能恢復到先前的狀態。
  • 如果一個用接口來讓其他對象直接得到的這些狀態,將會暴露對象的實現細節并破壞對象的封裝性。

效果

  • 保持封裝邊界。
  • 簡化了 Originator。
  • 定義窄接口和寬接口。
  • 使用和維護 Memento 的潛在代價。

相關模式

  • 可以使用 Memento 存儲 Command 的內部狀態,以支持撤銷操作。
  • Memento 可以使用 Iterator 進行迭代。

實現

Caretaker 向 Originator 請求一個 Memento,保留一段時間后,將其送回 Originator。

實現方式(一):Memento 模式結構樣式代碼。

Memento 有兩個接口:一個為 Originator 所使用的寬接口,一個為其他對象所使用的窄接口。

 1 namespace MementoPattern.Implementation1
 2 {
 3   public class Memento
 4   {
 5     private readonly string _state;
 6 
 7     public Memento(string state)
 8     {
 9       _state = state;
10     }
11 
12     public string GetState()
13     {
14       return _state;
15     }
16   }
17 
18   public class Originator
19   {
20     public string State { get; set; }
21 
22     public Memento CreateMemento()
23     {
24       return (new Memento(State));
25     }
26 
27     public void SetMemento(Memento memento)
28     {
29       State = memento.GetState();
30     }
31   }
32 
33   public class Caretaker
34   {
35     public Memento Memento { get; set; }
36   }
37 
38   public class Client
39   {
40     public void TestCase1()
41     {
42       var originator = new Originator { State = "State A" };
43       Console.WriteLine(originator.State);
44 
45       var memento = originator.CreateMemento();
46       var caretaker = new Caretaker { Memento = memento };
47 
48       originator.State = "State B";
49       Console.WriteLine(originator.State);
50 
51       originator.SetMemento(caretaker.Memento);
52       Console.WriteLine(originator.State);
53     }
54   }
55 }

 

設計模式之美》為 Dennis Gao 發布于博客園的系列文章,任何未經作者本人同意的人為或爬蟲轉載均為耍流氓。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()