Tuesday, March 5, 2013

Think in Reverse (Class Diagrams) - Composition,Aggregation & Association

If you are looking for something simple to understand the difference between association, aggregation, and composition, Then this article will be useful to you.

There are three primary inter-object relationships: association, aggregation, and composition. Using the correct relationship is important for placing implicit restrictions on the visibility and propagation of changes to the related classes, matters which play a major role in reducing system complexity.

Association :
A person and a company are two individual entities, but a person can work in a company, and he is called an employee... So the employee has an existence in the outer world as a person. So even if the company perishes, but the person will not perish.

 public class Example {  
   public static void main(String[] args) {  
     Person p1 = new Person("Vishal");  
     Company abc = new Company(p1);  
   }  
 }  
 class Person{  
   String name;  
   public Person(String name) {  
     this.name = name;  
   }  
 }  
 class Company{  
   Person employee;  
   public Company(Person p1) {  
     employee = p1;  
   }  
 }  

Composition (Non-Shared Association):
 public Class Client  
 {  
   BankAccount acc = new BankAccount();  
   public void addMoneyToBankAccount(decimal amount)  
   {       
     acc.AddMoney(amount);  
   }  
   public decimal CheckBalance()  
   {  
     return acc.CheckAccountBalance();  
   }  
 }  

** Points to notice: Client class has defined the BankAccount attribute (acc) as a class variable and initialized at the point of declaration. If I simply say, BankAccount is a part-of Client.   If inheritance gives us 'is-a' and composition gives us 'part-of', we could argue that aggregation gives us a 'has-a' relationship.

Aggregation (Shared Association): 
 Class Client  
 {  
   BankAccount acc;  
   public Client(BankAccount p_acc)  
   {  
    acc=p_acc;  
   }  
   public decimal CheckBalance()  
   {  
     return acc.CheckAccountBalance();  
   }  
 }  

Within aggregation, the lifetime of the part is not managed by the whole. The client class is only keeping a reference for BankAccount class, but is not controlling its object lifetime.

Even after the client object is destroyed, BankAccount object used within can be assigned for another Client.

No comments:

Post a Comment