c#設計模式之組合模式(composition pattern)
阿新 • • 發佈:2019-01-28
using System;
using System.Collections;
///<summary>
/// Composition pattern example.
///</summary>
/// Interface
publicinterface IContent
{
void Add(IContent ic);
void Remove(IContent ic);
void Display();
}
publicclass Leaf : IContent
{
privateint value;
publicvoid Add(IContent ic)
{
}
publicvoid Remove(IContent ic)
{
}
publicvoid Display()
{
Console.WriteLine("Leaf"+ value);
}
public Leaf(int val)
{
value = val;
}
}
publicclass Tree : IContent
{
privateint value;
private ArrayList al =null;
publicvoid Add(IContent ic)
{
if (al ==null)
{
al =new ArrayList();
}
al.Add(ic);
}
publicvoid Remove(IContent ic)
{
if (al !=null)
{
al.Remove(ic);
}
}
publicvoid Display()
{
Console.WriteLine( "Tree"+ value);
foreach (IContent ic in al)
{
ic.Display();
}
}
public Tree(int val)
{
value = val;
}
}
publicclass MyMain
{
publicstaticvoid Main()
{
Tree root =new Tree(10000);
Tree tr1 =new Tree(1000);
Leaf lf1=new Leaf(10);
Leaf lf2 =new Leaf(20);
Leaf lf3 =new Leaf(30);
tr1.Add(lf1);
tr1.Add(lf2);
root.Add(tr1);
root.Add(lf3);
root.Display();
}
}
using System.Collections;
///<summary>
/// Composition pattern example.
///</summary>
/// Interface
publicinterface IContent
{
void Add(IContent ic);
void Remove(IContent ic);
void Display();
}
publicclass Leaf : IContent
{
privateint value;
publicvoid Add(IContent ic)
}
publicvoid Remove(IContent ic)
{
}
publicvoid Display()
{
Console.WriteLine("Leaf"+ value);
}
public Leaf(int val)
{
value = val;
}
}
publicclass Tree : IContent
{
privateint value;
private ArrayList al =null;
publicvoid
{
if (al ==null)
{
al =new ArrayList();
}
al.Add(ic);
}
publicvoid Remove(IContent ic)
{
if (al !=null)
{
al.Remove(ic);
}
}
publicvoid Display()
{
Console.WriteLine(
foreach (IContent ic in al)
{
ic.Display();
}
}
public Tree(int val)
{
value = val;
}
}
publicclass MyMain
{
publicstaticvoid Main()
{
Tree root =new Tree(10000);
Tree tr1 =new Tree(1000);
Leaf lf1=new Leaf(10);
Leaf lf2 =new Leaf(20);
Leaf lf3 =new Leaf(30);
tr1.Add(lf1);
tr1.Add(lf2);
root.Add(tr1);
root.Add(lf3);
root.Display();
}
}
以上只是組合模式的一個簡單的實現。李建忠老師說得對,要理解設計模式還是要理解為什麼要這麼做。 上例中有一個樹類和一個葉子類。對於葉子類我們沒必要計較什麼,因為它是一個樹的最末端,該怎麼使用直接使用就是了。麻煩的是那棵樹,樹裡面有個數祖,數祖裡面放置的可能是最簡單的葉子,但也有可能是一顆樹枝。該怎麼對樹物件裡面的這些資料進行處理呢?
如果是在客戶端程式碼中直接使用(這時涉及到對資料的判斷從而有分別的處理:是樹還是葉子),但這時的問題就是客戶端程式碼與類的實現之間,耦合度太大。
解決的辦法就是利用一個迭代在類的內部建立一個樹狀結構,將實現完全封裝,在客戶程式碼中根本看不到類是怎樣具體對資料進行處理的,從而到達到解耦的目的。利用《設計模式》裡面的話就是:將物件組合成樹狀結構以表示“部分—整體”的層次結構。Composite使得使用者對單個物件和組合物件的使用具有一致性。
這句話可謂精闢之至。