โ† Back to OOP Concepts
๐Ÿงฉ
Relationships

Aggregation

A "has-a" relationship where a container holds references to objects that can exist independently of it โ€” a whole-part relationship without ownership.

The Problem

Some objects logically belong to a group, but shouldn't be destroyed when the group is destroyed โ€” deleting a Playlist shouldn't delete the Songs it contains.

How It Works

  • โ€บThe "part" can exist independently of the "whole" and can be shared across multiple wholes
  • โ€บRepresented as a collection of references, not owned instances
  • โ€บDestroying the container does not destroy its parts
  • โ€บA weaker form of ownership than composition

When to Use

โœ“A Playlist containing Songs that also exist outside the playlist
โœ“A Department containing Employees who could move to another department
โœ“A Team referencing Players who exist independently of the team

Real-World Examples

๐ŸŽ
iOS

An array of shared model objects referenced by multiple view controllers

๐Ÿค–
Android

A Playlist entity referencing Song IDs stored in a Room database

๐ŸŒ
Web

A shopping cart holding references to Product objects from a catalog

Code Examples

Swift
class Song {
    let title: String
    init(title: String) { self.title = title }
}

class Playlist {
    let name: String
    private(set) var songs: [Song] = []

    init(name: String) { self.name = name }

    func add(_ song: Song) {
        songs.append(song)
    }
}

let bohemianRhapsody = Song(title: "Bohemian Rhapsody")
let playlist = Playlist(name: "Road Trip")
playlist.add(bohemianRhapsody)
// bohemianRhapsody still exists even if `playlist` is deallocated