这是我的页面头部

聚合和组合 (Aggregation and Composition)

Aggregation and Composition
from: UML Distilled: A Brief Guide to the Standard Object Modeling Language, Third Edition

One of the most frequent sources of confusion in the UML is aggregation and composition. It's easy to explain glibly: Aggregation is the part-of relationship. It's like saying that a car has an engine and wheels as its parts. This sounds good, but the difficult thing is considering what the difference is between aggregation and association.

In the pre-UML days, people were usually rather vague on what was aggregation and what was association. Whether vague or not, they were always inconsistent with everyone else. As a result, many modelers think that aggregation is important, although for different reasons. So the UML included aggregation (Figure 5.3) but with hardly any semantics. As Jim Rumbaugh says, "Think of it as a modeling placebo" [Rumbaugh, UML Reference].
Figure 5.3. Aggregation

聚合和组合

UML中最容易混淆的概念就是聚合和组合。聚合的概念容易理解:聚合是“部分--整体”的关系,就像汽车有一个发动机和四个轮子。听起来解释得很明白。但问题是:聚合和组合有什么不同。
在还没有UML的时候,人们通常把聚合和关联混为一淡。区分和不区分这两个概念的人各执一词而且互不妥协。结果,许多建模师认为聚合是重要的,尽管理由各不相同。因此,UML包含了聚合(图5.3),但几乎没有任何语意。正如Jim Rumbaugh 所言,“就当它是一种建模安慰剂”。

As well as aggregation, the UML has the more defined property of composition. In Figure 5.4, an instance of Point may be part of a polygon or may be the center of a circle, but it cannot be both. The general rule is that, although a class may be a component of many other classes, any instance must be a component of only one owner. The class diagram may show multiple classes of potential owners, but any instance has only a single object as its owner.

Figure 5.4. Composition



UML中有一个与聚合功能类似的属性,叫做“组合(composition)”。在图5.4中,point的一个实例可以是多边形的一部分,也可以是一个圆的圆心,但不能同时充当这两种角色。组合的规则是:一个类可以用于组成许多其它的类,但这个类的实例却只能有一个宿主(拥有者)。可能类图上显示一个类有多个潜在的宿主类,但是这个类的任一实例只能有一个(其它类的)对象作为它的属主。


You'll note that I don't show the reverse multiplicities in Figure 5.4. In most cases, as here, it's 0..1. Its only other possible value is 1, for cases in which the component class is designed so that it can have only one other class as its owner.
可能你注意到,在图5.4中,我没有显示反向的一对多关系。多数情况下,这个值是 0..1,其唯一的另一个可能值是1。这样设计成员类是为了限制这个类只能再把一个类作为其宿主类。

The "no sharing" rule is the key to composition. Another assumption is that if you delete the polygon, it should automatically ensure that any owned Points also are deleted.

“非共享”特性是组合的关键。另一个假定是:如果删除了一个多边形,这个多边形上的所有点也必然都不存在了。


posted @ 2007-10-30 19:16  范晨鹏  阅读(4634)  评论(2编辑  收藏  举报