技术开发 频道

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


【IT168技术文档】

  合成模型模式属于对象的结构模式,有时又叫做部分-整体模式。合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式可以使客户端将单纯元素与复合元素同等看待。如文件夹与文件就是合成模式的典型应用。根据模式所实现接口的区别,合成模式可分为安全式和透明式两种。



  安全式的合成模式要求管理聚集的方法只出现在树枝构件类中,而不出现在树叶构件类中。类图如下所示:

  涉及到三个角色:



  抽象构件(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
0
相关文章