Design Patterns in Swift — Mediator

Ruslan Dzhafarov
5 min readJan 23, 2023

The Mediator design pattern is a behavioral design pattern that allows objects to communicate with each other without having direct references to each other. The pattern introduces a mediator object that acts as a facilitator for communication between objects.

Here’s an example of using the Mediator pattern in Swift to control communication between different Airplane objects:

protocol Airplane {
var name: String { get }
func receive(message: String, from: Airplane)
func send(message: String, to: Airplane)
}

class Boeing747: Airplane {
var name: String = "Boeing 747"
private var mediator: AirTrafficControl

init(mediator: AirTrafficControl) {
self.mediator = mediator
self.mediator.register(plane: self)
}

func receive(message: String, from: Airplane) {
print("\(name) received message: '\(message)' from \(from.name)")
}

func send(message: String, to: Airplane) {
mediator.send(message: message, from: self, to: to)
}
}

class AirTrafficControl {
private var airplanes: [Airplane] = []

func register(plane: Airplane) {
airplanes.append(plane)
}

func send(message: String, from: Airplane, to: Airplane) {
to.receive(message: message, from: from)
}
}

let atc = AirTrafficControl()
let boeing747_1 = Boeing747(mediator: atc)
let boeing747_2…

--

--

Ruslan Dzhafarov

Senior iOS Developer since 2013. Sharing expert insights, best practices, and practical solutions for common development challenges