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