Composition vs Aggregation

Composition and aggregation both are different forms of association. If an association is more like a 'is a' relationship, both of these are more like a 'has a' relationship. It is more like a whole/part relationship or an owner/owned relationship. For example, an automobile has an engine or the other way round, engine is 'a part of' an automobile. What's the difference?

 Composition is a higher degree of association than aggregation. The only major difference in terms of objects is the management of lifetime of the objects. In case of composition the lifetime of the owned object is the responsibility of the owner object.

 For example.

public class Person

{

  public string FirstName {get; set;}

  public string FirstName {get; set;}

  public Address CompleteAddress {get; set;}

}

 

public static void Main()

{

         Person person = new Person();

         person.CompleteAddress = new Address();

         //This line explains that it is a composition as the lifetime of CompleteAddress object depends on the person object.

        //The moment 'person' is garbage collected, the CompleteAddress object is also garbage collected.
}

 

Let's take another example for Aggregation

public void Car

{

     public string VIN { get; set; }

     public Engine MyEngine { get; set; }

     public Car(Engine engine)

     {

           this.MyEngine = engine;

     }

}

 

Now let's call it in Main.

public static void Main()

{

      Engine engine = Engine.GetEngine();

      //Just gives us an object. We could have 'newed' it also. However, a good place to inject dependency.

      Car car = new Car(engine);

      // 'engine' object here does not depend on the lifetime of the 'car' object.

      // So it is a case of aggregation.

     // However, car.MyEngine is an example of composition.

     // Most of the times when we code, we do something like Car car = new Car(new Engine());

     // In this case, we do not retain the Engine object as it is created in the constructor call/

     // That is the case when people start getting confused between aggregation and composition.

}

 In UML, the symbol for aggregation is a quadrilateral more like a rhombus which is unfilled and for composition it a filled rhombus.

 Hope that helps.

2 Comments

Comments have been disabled for this content.