Saturday, October 16, 2010

Aggregation Vs Composition

Before I share my insights about these subjects I just want to make clear that I am not claiming that I know everything nor I'm an expert. In fact, me myself desires to understand more about these subjects and that's one of the main reasons why I'm blogging these.

Aggregation... Composition... Association... Generalization... Realization... These are the terms that we software developers are very familiar with. Really? I know most of you are actually tired of reading, commenting, answering, and  posting explanation regarding these subjects on many different web sites and forums. But for those who still don't fully understand, this blog is for you!

Aggregation
  • A relationship between an "Aggregate" and a "Component".
  • A whole/part relationship between objects, classes, and components.
  • A weak "HAS A" relationship between  an "Aggregate" and a "Component", meaning the Component does not belong to the Aggregate.
  • The creation and destruction of the Component is done outside the Aggregate, meaning the life cycle of the Component is not controlled by the Aggregate.
  • When the Aggregate is destroyed, the Component may survive.
  • In UML, the symbol of aggregation is a non-filled diamond arrow.
  • The figure below shows an example of aggregation. The School(aggregate) 'has a' list of Students(component). 
  • Sample code for this UML design (diagram) is show below. Please read the comments within the code.


Composition

  • A relationship between a "Composite" and a "Component".
  • Similar with aggregation relationship except that the Component fully controls the lifetime of the Component.
  • strong "HAS A" relationship between  an "Composite" and a "Component", meaning the Component belongs to the Composite.
  • The creation and destruction of the Component is done inside the Composite.
  • When the Composite is destroyed, the Component will also be destroyed.
  • In UML, the symbol of composition is a filled-diamond arrow.
  • The figure below shows an example of composition. The Car(composite) 'has an'  Engine(component). 
  • Sample code for this UML design (diagram) is show below.  Please read the comments within the code.

I hope that I can help someone with this blog. If you have additional information or if you think that there are mistakes above, feel free to comment. I will be happy to answer more questions and also learn from you!

Note: I will update this blog and add information on dependency, association, generalization, and realization.