โ 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