Understanding Association, Aggregation, and Composition

Author:
 
 
 
In this article we will try to understand 3 important concepts association, aggregation and composition.
 

Table of contents

Introduction

In this article, we will try to understand three important concepts: association, aggregation, and composition.

We will also try to understand in what kind of scenarios we need them. These three concepts have really confused a lot of developers and in this article, my attempt would be to present the concepts in a simplified manner with some real world examples.

Extracting real world relationships from a requirement

The whole point of OOP is that your code replicates real world objects, thus making your code readable and maintainable. When we say real world, the real world has relationships. Let’s consider the simple requirement listed below:

  1. Manager is an employee of XYZ limited corporation.
  2. Manager uses a swipe card to enter XYZ premises.
  3. Manager has workers who work under him.
  4. Manager has the responsibility of ensuring that the project is successful.
  5. Manager's salary will be judged based on project success.

If you flesh out the above five point requirement, we can easily visualize four relationships:-

  • Inheritance
  • Aggregation
  • Association
  • Composition

Let’s understand them one by one.

Requirement 1: The IS A relationship

If you look at the first requirement (Manager is an employee of XYZ limited corporation), it’s a parent child relationship or inheritance relationship. The sentence above specifies that Manager is a type of employee, in other words we will have two classes: parent class Employee, and a child class Manager which will inherit from the Employee class.

Note: The scope of this article is only limited to aggregation, association, and composition. We will not discuss inheritance in this article as it is pretty straightforward and I am sure you can get 1000s of articles on the net which will help you in understanding it.

Requirement 2: The Using relationship: Association

Requirement 2 is an interesting requirement (Manager uses a swipe card to enter XYZ premises). In this requirement, the manager object and the swipe card object use each other but they have their own object life time. In other words, they can exist without each other. The most important point in this relationship is that there is no single owner.

The above diagram shows how the SwipeCard class uses the Manager class and the Manager class uses the SwipeCard class. You can also see how we can create objects of the Manager class and SwipeCard class independently and they can have their own object life time.

This relationship is called the “Association” relationship.

Requirement 3: The Using relationship with Parent: Aggregation

The third requirement from our list (Manager has workers who work under him) denotes the same type of relationship like association but with a difference that one of them is an owner. So as per the requirement, the Manager object will own Worker objects.

The child Worker objects can not belong to any other object. For instance, a Worker object cannot belong to a SwipeCard object.

But… the Worker object can have its own life time which is completely disconnected from the Manager object. Looking from a different perspective, it means that if the Manager object is deleted, the Worker object does not die.

This relationship is termed as an “Aggregation” relationship.

Requirements 4 and 5: The Death relationship: Composition

The last two requirements are actually logically one. If you read closely, the requirements are as follows:

  1. Manager has the responsibility of ensuring that the project is successful.
  2. Manager's salary will be judged based on project success.

Below is the conclusion from analyzing the above requirements:

  1. Manager and the project objects are dependent on each other.
  2. The lifetimes of both the objects are the same. In other words, the project will not be successful if the manager is not good, and the manager will not get good increments if the project has issues.

Below is how the class formation will look like. You can also see that when I go to create the project object, it needs the manager object.

This relationship is termed as the composition relationship. In this relationship, both objects are heavily dependent on each other. In other words, if one goes for garbage collection the other also has to be garbage collected, or putting from a different perspective, the lifetime of the objects are the same. That’s why I have put in the heading “Death” relationship.

Putting things together

Below is a visual representation of how the relationships have emerged from the requirements.

The source code

You can download the sample source code for this article.

Summarizing

To avoid confusion henceforth for these three terms, I have put forward a table below which will help us compare them from three angles: owner, lifetime, and child object.

 AssociationAggregationComposition
OwnerNo ownerSingle ownerSingle owner
Life timeHave their own lifetimeHave their own lifetimeOwner's life time
Child objectChild objects all are independentChild objects belong to a single parentChild objects belong to a single parent

Video on Association, Aggregation, and Composition

I have also added a video in case you do not want to read this long article.

<OBJECT type="application/x-shockwave-flash" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=3,0,0,0" WIDTH="640" HEIGHT="360" data="http://www.youtube.com/v/0po_wmSEW1Q?version=3&feature=player_detailpage"></OBJECT>

Just a note: I have recorded around 500 videos, do have a look at my videos on .NET, OOP, SQL Server, WCF, Silver light , LINQ , VSTS, SharePoint, Design Patterns, UML and a lot more.

Thanks for reading my article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

<think> 嗯,用户现在聚焦在Aggregation(聚合)和Composition(组合)的区别上,而且特别要求参考站内引用内容。用户之前已经了解了UML六种基本关系,现在想深入理解这两种容易混淆的整体-部分关系。 从用户引用的材料看,ta手头至少有四份参考资料:[1]强调生命周期独立性差异,[2]用"共享式/独占式"作比喻,[3]用数据库表和几何图形举例,[4]则用教室-教师、房屋-房间的经典案例。有趣的是这些材料存在共识点:组合是更强的聚合,区别核心在于部分能否独立存在。 需要特别注意用户引用的[3]提到UML符号差异——空心菱形和实心菱形,这个视觉线索在实际绘图时很重要。另外[4]的"death relationship"说法很生动,但中文用"同生共死"更符合语境。用户似乎偏好具体案例,所以我会重点展开房屋-房间的比喻。 用户可能正在画类图时遇到困惑,或是代码实现时不确定该用成员对象还是指针。ta连续两次追问这个点,说明实际工作需要明确区分。考虑到ta之前能提出专业的UML问题,应该具备OOP基础,可以适当使用"生命周期""强聚合"等术语。 需要澄清一个易错点:引用[3]说删除用户表需同时删用户信息表,这其实是数据库级联删除,并不完全等同于组合关系——组合是设计层面的约束。在解释时要区分设计概念和具体实现技术。 最后要注意用户要求的中文回答和LaTeX格式。虽然这个问题不涉及公式,但后续若讨论关联多重性(如1..*)就需要用$n..m$的数学表达。 </think>Aggregation(聚合)和Composition(组合)是UML中描述整体-部分关系的两种关联类型,核心区别在于**部分对象的生命周期独立性**和**所有权强度**: --- ### 1. **Aggregation(聚合)** - **UML符号**:空心菱形箭头 + 实线(菱形指向整体) ```mermaid classDiagram class Car class Engine Car o-- Engine : Aggregation ``` - **核心特征**: - **弱所有权**:整体(如`Car`)拥有部分(如`Engine`),但部分可独立存在 - **生命周期独立**:整体销毁时,部分不会被自动销毁(例:汽车报废后,发动机可被回收重用) - **共享性**:部分可被多个整体共享(如一个发动机可安装到不同汽车) - **语义**:**"has-a"关系**(整体拥有部分,但部分不依赖整体存活) > *例:* 学校(`School`)与教师(`Teacher`)——学校关闭后教师仍可去其他学校任职[^3][^4]。 --- ### 2. **Composition(组合)** - **UML符号**:实心菱形箭头 + 实线(菱形指向整体) ```mermaid classDiagram class House class Room House *-- Room : Composition ``` - **核心特征**: - **强所有权**:整体(如`House`)完全控制部分(如`Room`)的生命周期 - **生命周期绑定**:整体销毁时,所有部分同步销毁(例:房屋拆除后,所有房间不复存在) - **独占性**:部分仅属于一个整体,不可共享 - **语义**:**"contains-a/part-of"关系**(部分是整体的不可分割组件) > *例:* 人体(`Body`)与心脏(`Heart`)——人体死亡后心脏无法独立存活[^3][^4]。 --- ### 关键区别总结 | **维度** | **Aggregation(聚合)** | **Composition(组合)** | |------------------|-------------------------|-------------------------| | **生命周期依赖** | 部分独立存在 | 部分依赖整体存活 | | **所有权强度** | 弱(共享) | 强(独占) | | **UML符号** | ◇ 空心菱形 | ◆ 实心菱形 | | **代码实现** | 整体持有部分的对象引用 | 整体直接创建部分对象 | | **典型例子** | 汽车与发动机 | 房屋与房间 | --- ### 本质区别的数学表达 设整体对象为 $W$(Whole),部分对象为 $P$(Part): - **聚合**:$P$ 的生存周期满足 $L(P) \not\subset L(W)$ (部分生命周期不依赖于整体) - **组合**:$L(P) \subset L(W)$ (部分生命周期是整体生命周期的子集)[^3][^4] > **简单记忆**: > - 聚合:**"整体没了,部分还在"**(如班级解散,学生仍在) > - 组合:**"整体没了,部分消亡"**(如大树倒下,树叶枯萎)[^2][^4]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值