Composition
Strong ownership - parts cannot exist without the whole.
Composition is a “has-a” relationship where one class contains another, and the contained class cannot exist independently. It represents a strong ownership relationship with tied lifecycles.
What is Composition?
Section titled “What is Composition?”Composition represents:
- “Has-a” relationship (strong ownership)
- Parts cannot exist independently of the whole
- Parts belong to only one whole
- Lifecycle dependency - parts are destroyed when whole is destroyed
Key Characteristics
Section titled “Key Characteristics”- Strong ownership - Container owns the parts
- Dependent lifecycle - Parts cannot exist without container
- Single ownership - Parts belong to only one container
- Filled diamond in UML diagrams
Basic Composition Example
Section titled “Basic Composition Example”Visual Representation
Section titled “Visual Representation”Real-World Example: Order System
Section titled “Real-World Example: Order System”Composition vs Aggregation
Section titled “Composition vs Aggregation”| Feature | Composition | Aggregation |
|---|---|---|
| Ownership | Strong | Weak |
| Lifecycle | Dependent | Independent |
| Multi-ownership | No | Yes |
| UML Symbol | Filled diamond | Hollow diamond |
| Example | Car → Engine | University → Students |
Key Takeaways
Section titled “Key Takeaways”When to Use Composition
Section titled “When to Use Composition”Use Composition when:
- Parts cannot exist without the whole
- Parts belong to only one whole
- Lifecycle is tied together
- Relationship is essential and permanent
- Parts are created by the whole
Examples:
- Car → Engine (engine doesn’t exist without car)
- Order → OrderItems (items don’t exist without order)
- House → Room (rooms don’t exist without house)
- Document → Paragraph (paragraphs don’t exist without document)
- Computer → CPU (CPU doesn’t exist without computer)