官术网_书友最值得收藏!

Aggregation and composition

We encountered aggregation in the example of the Warehouse class. The Warehouse class stores an array of Products. In more general terms, it can be called an association, but to strongly emphasize the exact containment, we use the term aggregation or composition. In the case of aggregation, the class that contains an instance or instances of other classes could be instantiated without the aggregate. This means that we can create and use a Warehouse object without necessarily creating Product objects contained in the Warehouse.

Another example of aggregation is the Car and the Person. A Car can contain a Person object (as a driver or passenger) since they are associated with each other, but the containment is not strong. We can create a Car object without a Driver in it, as follows:

class Person; // forward declaration
class Engine { /* code omitted for brevity */ };
class Car {
public:
Car();
// ...
private:
Person* driver_; // aggregation
std::vector<Person*> passengers_; // aggregation
Engine engine_; // composition
// ...
};

The strong containment is expressed by composition. For the Car example, an object of the Engine class is required to make a complete Car object. In this physical representation, the Engine member is automatically created when a Car is created. 

The following is the UML representation of aggregation and composition:

When designing classes, we have to decide on their relationship. The best way to define the composition between the two classes is the has-a relationship test. A Car has-a Engine, because a car has an engine. Any time you can't decide whether the relationship should be expressed in terms of composition, ask the has-a question. Aggregation and composition are somewhat similar; they just describe the strength of the connection. For aggregation, the proper question would be can have a; for example, a Car can have a driver (of the Person type); that is, the containment is weak. 

主站蜘蛛池模板: 双辽市| 泾源县| 涿鹿县| 涿鹿县| 凤阳县| 乐亭县| 十堰市| 青河县| 江永县| 嘉义市| 赣州市| 大理市| 土默特左旗| 叶城县| 保德县| 高安市| 咸阳市| 肇州县| 墨竹工卡县| 杭锦旗| 青冈县| 长治县| 二连浩特市| 米易县| 梁河县| 合山市| 叙永县| 阳谷县| 德昌县| 古蔺县| 桦川县| 临汾市| 搜索| 盐边县| 海南省| 湖口县| 曲周县| 盘山县| 兰溪市| 深水埗区| 绵阳市|