โ Back to OOP Concepts
๐งฑ
Relationships
Composition
A strong "has-a" relationship where the part's lifecycle is bound to the whole โ when the container is destroyed, so are its parts.
The Problem
Some objects are meaningless without their owner โ an Engine doesn't make sense detached from its Car. Modeling this with plain shared references doesn't express that lifecycle dependency.
How It Works
- โบThe contained object is created and destroyed along with its owner
- โบThe part typically has no independent identity outside the whole
- โบFavor composition over inheritance for flexible, loosely-coupled designs
- โบUsually implemented by instantiating the part directly inside the whole's constructor
When to Use
โAn object owns components that are integral to it (Car โ Engine, House โ Rooms)
โBuilding complex behavior by combining smaller objects rather than subclassing
โWhen the "part" should never be shared between multiple "wholes"
Real-World Examples
๐
iOS
A view controller owning and managing the lifecycle of its child views
๐ค
Android
An Activity owning Fragments that are created and destroyed with it
๐
Web
A Car class instantiating its own Engine instance in its constructor
Code Examples
Swift
class Engine {
let horsepower: Int
init(horsepower: Int) { self.horsepower = horsepower }
func start() -> String { "Engine roaring with \(horsepower) hp" }
}
class Car {
private let engine: Engine // owned โ created and destroyed with the Car
init(horsepower: Int) {
engine = Engine(horsepower: horsepower)
}
func start() -> String {
engine.start()
}
}
let car = Car(horsepower: 300)
print(car.start()) // "Engine roaring with 300 hp"