設計模式c#語言描述——合成(Composite)模式
*本文參考了《JAVA與模式》的部分內容,適合于設計模式的初學者。
合成模型模式屬于對象的結構模式,有時又叫做部分-整體模式。合成模式將對象組織到樹結構中,可以用來描述整體與部分的關系。合成模式可以使客戶端將單純元素與復合元素同等看待。如文件夾與文件就是合成模式的典型應用。根據模式所實現接口的區別,合成模式可分為安全式和透明式兩種。
安全式的合成模式要求管理聚集的方法只出現在樹枝構件類中,而不出現在樹葉構件類中。類圖如下所示:
涉及到三個角色:
抽象構件(Component):這是一個抽象角色,它給參加組合的對象定義公共的接口及其默認的行為,可以用來管理所有的子對象。合成對象通常把它所包含的子對象當做類型為Component的對象。在安全式的合成模式里,構件角色并不定義出管理子對象的方法,這一定義由樹枝構件對象給出。
樹葉構件(Leaf):樹葉對象是沒有下級子對象的對象,定義出參加組合的原始對象的行為。
樹枝構件(Composite):代表參加組合的有下級子對象的對象。樹枝構件類給出所有的管理子對象的方法,如Add(),Remove()等。
Component:
public interface Component
{
void sampleOperation();
}// END INTERFACE DEFINITION Component
Leaf:
public class Leaf : Component
{
public void sampleOperation()
{
}
}// END CLASS DEFINITION Leaf
Composite:
public class Composite :Component
{
private ArrayList componentList=new ArrayList();
public void sampleOperation()
{
System.Collections.IEnumerator myEnumerator = componentList.GetEnumerator();
while ( myEnumerator.MoveNext() )
{
((Component)myEnumerator.Current).sampleOperation();
}
}
public void add(Component component)
{
componentList.Add (component);
}
public void remove(Component component)
{
componentList.Remove (component);
}
}// END CLASS DEFINITION Composite
與安全式的合成模式不同的是,透明式的合成模式要求所有的具體構件類,不論樹枝構件還是樹葉構件,均符合一個固定的接口。類圖如下所示:
抽象構件(Component):這是一個抽象角色,它給參加組合的對象定義公共的接口及其默認的行為,可以用來管理所有的子對象。要提供一個接口以規范取得和管理下層組件的接口,包括Add(),Remove()。
樹葉構件(Leaf):樹葉對象是沒有下級子對象的對象,定義出參加組合的原始對象的行為。樹葉對象會給出Add(),Remove()等方法的平庸實現。
樹枝構件(Composite):代表參加組合的有下級子對象的對象。定義出這樣的對象的行為。
Component:
public interface Component
{
void sampleOperation();
void add(Component component);
void remove(Component component);
}// END INTERFACE DEFINITION Component
Leaf:
public class Leaf : Component
{
private ArrayList componentList=null;
public void sampleOperation()
{
}
public void add(Component component)
{
}
public void remove(Component component)
{
}
}// END CLASS DEFINITION Leaf
Composite:
public class Composite :Component
{
private ArrayList componentList=new ArrayList();
public void sampleOperation()
{
System.Collections.IEnumerator myEnumerator = componentList.GetEnumerator();
while ( myEnumerator.MoveNext() )
{
((Component)myEnumerator.Current).sampleOperation();
}
}
public void add(Component component)
{
componentList.Add (component);
}
public void remove(Component component)
{
componentList.Remove (component);
}
}// END CLASS DEFINITION Composite
|