组合模式——Composite

1. Composite 定义

         将对象以树形结构组织起来,以达成“部分 - 整体”的层次结构,使得客户端对单个对象和组合对象的使用具有一致性。

         想到 Composite 就应该想到树形结构图。组合体内这些对象都有共同接口。当组合体一个对象的方法被调用时, Composite 将遍历整个“子树”,寻找同样包含这个方法的对象执行之。

         类似 Chain of Responsibility 模式(责任链)。

 

2. Composite 好处 (目的 ):

         The intent of the COMPOSITE pattern is to let clients treat individual objects and compositions of objects uniformly .

         1. 简化调用:使客户端调用简单,客户端可以一致的使用组合结构或其中单个对象,用户就不必关注自己处理的是单个对象还是整个组合结构,这就简化了客户端代码。

         2. 容易组装:更容易在组合体内加入对象部件 . 客户端不必因为加入了新的对象部件而更改代码。

 

3. Composite 缺点

扫描二维码关注公众号,回复: 1226530 查看本文章

         1. 循环 Cycles

         在实现 Leaf Composite 两个类型的公共方法时,引入“递归 (recursive) ”机制;而“递归”,可能引入“循环 (Cycles) ”的危险。

         A. 对于某些方法,“有限循环 (a definite loop) ”是有意义的;但应该加入相应代码避免“无限循环 (an indefinite loop)

         B. 对于某些方法,循环导致“无意义”——例如, maxNumOfSteps()

         C. 不能保证 composites 的对象结构是 Tree ,因此不能保证节点只有一个双亲节点

        

 

4. Composite 使用 方法:

         When you model a composite, two powerful concepts emerge:

                   1) Design groups so that they can contain either individual items or other groups.

                   2) Define behaviors common to both individual objects and compositions.

 

         4.1   Composite Class Diagram:

 

图4.1 Composite设计模式

 

 

         4.2   假设 Composites 的对象结构为 Tree ,一个简单的例子实现 Composite 模式

         getMachineCount() 方法实现

 

         4.3   考虑到 Composites 的对象结构可能为 Tree ,有向无环图 DAG ,但更有可能为含有环的有向图

         boolean isTree(Set) 方法实现

         客户端均用 isTree() 调用

 

图4.2 4.3 Composite模式实例

 

*******************************************************************************

参见《设计模式》(板桥里人 http://www.jdon.com 2002/04/27

参见《 Java 设计模式》 P47 chapter5 composite

猜你喜欢

转载自chuanwang66.iteye.com/blog/1324646
今日推荐