《大話設計模式》讀書筆記(六)
寫在前面
本文上接:《大話設計模式》讀書筆記(五),這次來學習備忘錄模式、組合模式、迭代器模式。
13.備忘錄模式(Memento Pattern)
解決的問題
備忘錄模式可以在不破壞封裝性的前提下,捕獲一個物件的內部狀態,並且在物件之外儲存這個狀態,這樣以後就可將該物件恢復到原先儲存的狀態。
類圖結構
Originator
表示發起人,負責建立一個備忘錄,用來記錄當前時刻它的內部狀態,並可使用備忘錄恢復內部狀態。Memento
負責儲存Originator物件的內部狀態,並可防止Originator以外的其他物件訪問備忘錄Memento。備忘錄有兩個介面,CareTaker只能看到備忘錄的窄介面,它只能將備忘錄傳遞給其他物件。CareTaker
Originator:
class Originator{ private String state; public String state{ get{return state;} set {state = value;} } public Memento createMemento(){ return (new Memento(state)); } public void setMemento(Memento memento){ state = memento.state; } public void show(){ Console.WriteLine("State = " + state); } }
Memento:
class Memento{
private string state;
public Memento(string state){
this.state = state;
}
public string State{
get {return state;}
}
}
CareTaker:
class CareTaker{ private Memento memento; public Memento memento{ get {return memento;} set {memento = value;} } }
好處與壞處
備忘錄模式比較適用於功能比較複雜的,但需要維護或記錄屬性歷史的類。或者需要儲存的屬性只是眾多屬性中的一小部分的時候,可以根據儲存的備忘錄資訊恢復到前一狀態。缺點是比較消耗資源。如果類的成員變數過多,勢必會佔用比較大的資源,而且每一次儲存都會消耗一定的記憶體。
14.組合模式(Composite Pattern)
解決的問題
將物件組合成樹形結構以表示“部分-整體”的層次結構。組合模式使得使用者對單個物件和組合物件的使用具有一致性。
類圖結構
Component
為組合中的物件宣告介面,實現所有類共同介面的預設行為。宣告一個介面用於訪問和管理Component的子部件。
abstract class Component{
protected string name;
public Component(string name){
this.name = name;
}
public abstract void Add(Component c);
public abstract void Remove(Component c);
public abstract void Display(int depth);
}
Leaf
在組合中表示葉物件節點,葉子節點沒有子節點:
class Leaf : Compoent{
public Leaf(string name)
: base(name)
{}
public override void Add(Component c){
Console.WriteLine("Cannot add to a leaf");
}
public override void Remove(Component c){
Console.WriteLine("Cannot remove from a leaf");
}
public override void Display(int depth){
Console.WriteLine(new String("-",depth) + name);
}
}
Composite
定義為有枝的節點,用來儲存子部件。
class Composite : Compoent{
private List<Compoent> children = new List<Component>();
public Composite(string name) : base(name){}
public override void Add(Component c){
children.Add(c);
}
public override void Remove(Component c){
children.Remove(c);
}
public override void Display(int depth){
Console.WriteLine(new String("-",depth) + name);
foreach(Compoent component in children){
component.Display(depth + 2);
}
}
}
好處與壞處
組合模式定義了包含著基本物件和複雜的組合物件,組合物件又可以被組合,這樣不斷遞迴,就可以很好的實現功能了。但組合模式不容易限制組合中的構件。
15.迭代器模式(Iterator)
解決的問題
迭代器模式提供了一種方法順序訪問一個聚合物件中的各個元素,而不暴露該物件的內部表示。
類圖結構
這裡就不再上程式碼了,因為這個模式在很多語言中都有對應的實現。
好處與壞處
首先它支援以不同的方式遍歷一個聚合物件,且簡化了聚合類。但在一定程度上會增加系統的複雜度。
總結
總的來說,主要學習了三個設計模式。