What is the difference between aggregation, composition and dependency? [duplicate]
Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.
Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.
The above two are forms of containment (hence the parent-child relationships).
Dependency is a weaker form of relationship and in code terms indicates that a class uses another by parameter or return type.
Dependency is a form of association.
Aggregation and composition are almost completely identical except that composition is used when the life of the child is completely controlled by the parent.
Aggregation
Car -> Tires
The Tires
can be taken off of the Car
object and installed on a different one. Also, if the car gets totaled, the tires do not necessarily have to be destroyed.
Composition
Body -> Blood Cell
When the Body
object is destroyed the BloodCells
get destroyed with it.
Dependency
A relationship between two objects where changing one may affect the other.
Aggregation - separable part to whole. The part has a identity of its own, separate from what it is part of. You could pick that part and move it to another object. (real world examples: wheel -> car, bloodcell -> body)
Composition - non-separable part of the whole. You cannot move the part to another object. more like a property. (real world examples: curve -> road, personality -> person, max_speed -> car, property of object -> object )
Note that a relation that is an aggregate in one design can be a composition in another. Its all about how the relation is to be used in that specific design.
dependency - sensitive to change. (amount of rain -> weather, headposition -> bodyposition)
Note: "Bloodcell" -> Blood" could be "Composition" as Blood Cells can not exist without the entity called Blood. "Blood" -> Body" could be "Aggregation" as Blood can exist without the entity called Body.
An object associated with a composition relationship will not exist outside the containing object. Examples are an Appointment and the owner (a Person) or a Calendar; a TestResult and a Patient.
On the other hand, an object that is aggregated by a containing object can exist outside that containing object. Examples are a Door and a House; an Employee and a Department.
A dependency relates to collaboration or delegation, where an object requests services from another object and is therefor dependent on that object. As the client of the service, you want the service interface to remain constant, even if future services are offered.