设计模式c#语言描述——合成(Composite)模式

** 设计模式 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

Published At
Categories with Web编程
Tagged with
comments powered by Disqus