โ Back to OOP Concepts
๐
Relationships
Association
A general relationship where one object uses or interacts with another, without ownership โ both objects can exist independently.
The Problem
Modeling real-world interactions, like a Teacher teaching Students, requires representing a relationship between objects without implying that one controls the other's lifecycle.
How It Works
- โบObjects hold references to each other but each has an independent lifecycle
- โบCan be one-to-one, one-to-many, or many-to-many
- โบCan be unidirectional (one object knows about the other) or bidirectional
- โบThe weakest form of relationship โ simply "knows about" or "uses"
When to Use
โModeling collaborations between independent entities (Driver and Car)
โWhen neither object owns or controls the other's lifecycle
โRepresenting references/links between domain objects
Real-World Examples
๐
iOS
A delegate property pointing to an independent, unowned object
๐ค
Android
A ViewModel holding a reference to a Repository it does not own
๐
Web
A User object referencing a Department by ID, both stored independently
Code Examples
Swift
class Student {
let name: String
init(name: String) { self.name = name }
}
class Teacher {
let name: String
private var students: [Student] = []
init(name: String) { self.name = name }
func assign(_ student: Student) {
students.append(student)
}
func roster() -> [String] {
students.map { $0.name }
}
}
let teacher = Teacher(name: "Ms. Lee")
teacher.assign(Student(name: "Alice"))
teacher.assign(Student(name: "Bob"))
print(teacher.roster()) // ["Alice", "Bob"]