Aggregation vs Composition

Aggregation and Composition are types of associations in object-oriented programming. They both describe relationships between objects, but they have key differences in terms of ownership and lifecycle management.

Aggregation

Aggregation

  • Definition: Aggregation is a weak association where the child can exist independently of the parent.
  • Ownership: The parent object can contain or own a collection of child objects, but those child objects can exist independently of the parent.
  • Lifecycle: If the parent object is destroyed, the child objects can continue to exist.

Example: A Library contains Books. If the Library is destroyed, the Books still exist.

classDiagram
    class Library {
        +Book[] books
    }
    class Book {
    }

    Library "1" o-- "0..*" Book : Aggregation
  • In Mermaid Aggregation:
    • Represented by an open diamond (o--).
    • Indicates a “has-a” relationship where the parent can own the child, but the child can exist independently.
Link to original

Composition

Composition

  • Definition: Composition is a strong association where the child cannot exist independently of the parent.
  • Ownership: The parent object is responsible for the lifecycle of its child objects. The child objects do not exist without the parent.
  • Lifecycle: If the parent object is destroyed, the child objects are also destroyed.

Example: A House contains Rooms. If the House is destroyed, the Rooms are also destroyed.

classDiagram
    class House {
        +Room[] rooms
    }
    class Room {
    }

    House "1" *-- "0..*" Room : Composition

In Mermaid Composition:

  • Represented by a filled diamond (*--).
  • Indicates a “part-of” relationship where the parent strictly owns the child, and the child cannot exist without the parent.
Link to original

Mermaid Diagram

To visually explain the differences, we can use a Mermaid diagram:

classDiagram
    class Library {
        +Book[] books
    }
    class Book {
    }

    class House {
        +Room[] rooms
    }
    class Room {
    }

    Library "1" o-- "0..*" Book : Aggregation
    House "1" *-- "0..*" Room : Composition

Key Points

  • Use aggregation when the lifecycle of the child is independent of the parent.
  • Use composition when the child’s lifecycle is bound to the parent.

Understanding the difference between aggregation and composition helps in designing better object-oriented systems by appropriately managing relationships and lifecycles of objects.

Feel free to ask any questions or dive deeper into specific aspects of aggregation or composition!