Sunday 22 February 2015

Association Vs Aggregation Vs Compositiona

The three concepts are closely related, indeed. Aggregation and Composition are actually types of Association. 

Association is an 'Has-A' relationship. In Java you can think of any time a class has an member of of a different type, then there is an Association between them. So for example: 

  1. {  
  2.     private final Name name;  
  3.     private Costume currentClothes;  
  4.   
  5.     //...  
  6. }  
In this case, the Person Has-A name and Has-A Costume, so there is an Association between Person and Name, and Person and Costume. 

Aggregation and Composition are specializations of the Association relationship - they are both Has-A relationships, but the difference is the length of that relationship. In the above example, a Person probably has a single Name for the live of the Person, while the Person may have different Costumes depending on the situation. If this is the case then the relationship between Person and Name is Composition, and the relationship between Person and Costume is Aggregation. 

Composition is an Association where the containing Object is responsible for the lifetime of the contained Object. To show this in Java Person might have a constructor like this: 

  1. public class Person  
  2. {  
  3.     private final Name name;  
  4.   
  5.     public Person (String fName, String lName)  
  6.     {  
  7.         name = new Name(fName, lName);  
  8.     }  
  9.   
  10.     //...  
  11. }  

Typically there would be no 'setName(Name)' methods. The Person is responsible for creating the Name, and when the Person is destroyed then the Name should (usually) be as well. 

Aggregation is an Association relationship where the Association can be considered the containing class 'Owning' the contained class, and the lifetime of that relationship is not defined. 'Owning' can be determined as a single-direction Association. In the above example, the Person Has-A Costume, but the Costume would not Have-A Person.More importantly the Person to Costume Association is transient. In Java you can usually tell this because there are setter methods, or other means of adding / replacing the contained Object. So for the Person class you might have: 


  1. public class Person  
  2. {  
  3.     private Costume currentClothes;  
  4.   
  5.     public void setClothes(Costume clothes)  
  6.     {  
  7.         currentClothes = clothes;  
  8.     }  
  9.   
  10.     //...  
  11. }  

No comments:

Post a Comment