设计模式之十一:Composite(组合)—对象结构型模式

来源:互联网 发布:有限元法的软件 编辑:程序博客网 时间:2024/04/30 13:11

2014-05-28 星期三 21:41:44 

Composite,继续GOF。

Composite组合模式

1、Intent

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

将对象组合成树形结构以表示“部分 -整体”的层次结构。 Composite使得用户对单个对象和组合对象的使用具有一致性。

2、Also Known As
3、Motivation

The Composite pattern describes how to use recursive composition so that clients don't have to make this distinction.

The key to the Composite pattern is an abstract class that represents bothprimitives and their containers. For the graphics system, this class is Graphic. Graphic declares operations like Draw that are specific to graphical objects. It also declares operations that all composite objects share, such as operations for accessing and managing its children.

Composite模式描述了如何使用递归组合,使得用户不必对这些类进行区别,如下图所示。



Composite模式的关键是一个抽象类,它既可以代表图元,又可以代表图元的容器。在图形系统中的这个类就是 Graphic,它声明一些与特定图形对象相关的操作,例如 Draw。同时它也声明了所有的组合对象共享的一些操作,例如一些操作用于访问和管理它的子部件。


The Picture class defines an aggregate of Graphic objects. Picture implements Draw to call Draw on its children, and it implements child-related operations accordingly. Because the Picture interface conforms to the Graphic interface, Picture objects can compose other Pictures recursively.

The following diagram shows a typical composite object structure of recursively composed Graphic objects:

Picture类定义了一个 Graphic 对象的聚合。 Picture 的D r a w操作是通过对它的子部件调用Draw实现的, Picture还用这种方法实现了一些与其子部件相关的操作。由于 Picture接口与Graphic接口是一致的,因此 Picture对象可以递归地组合其他 Picture对象。下图是一个典型的由递归组合的 Graphic对象组成的组合对象结构。


4、Applicability

Use the Composite pattern when

●  you want to represent part-whole hierarchies of objects. 

​●  you want clients to be able to ignore the difference between compositions of objects and individual objects. 

   Clients will treat all objects in the composite structure uniformly. 


以下情况使用Composite模式:

 你想表示对象的部分 -整体层次结构。

​● 你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。

5、Structure

6、代码

Composite就是把Leaf也“看作”Component。

代码见开首的链接,很直观表述了此模式。



0 0