โ† 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"