Explaining the Observer Pattern

The observer design pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. This is also known as the publish-subscribe pattern.

Here is an example of the observer design pattern in Swift:

protocol Observer {
    func update(with temperature: Int)
}

protocol Subject {
    func registerObserver(_ observer: Observer)
    func removeObserver(_ observer: Observer)
    func notifyObservers()
}

class WeatherStation: Subject {
    private var temperature: Int
    private var observers: [Observer] = []

    init(temperature: Int) {
        self.temperature = temperature
    }

    func registerObserver(_ observer: Observer) {
        observers.append(observer)
    }

    func removeObserver(_ observer: Observer) {
        observers = observers.filter { $0 !== observer }
    }

    func notifyObservers() {
        for observer in observers {
            observer.update(with: temperature)
        }
    }

    func setTemperature(temperature: Int) {
        self.temperature = temperature
        notifyObservers()
    }
}

class TemperatureDisplay: Observer {
    func update(with temperature: Int) {
        print("Temperature is now: \(temperature)")
    }
}

let weatherStation = WeatherStation(temperature: 70)
let temperatureDisplay = TemperatureDisplay()

weatherStation.registerObserver(temperatureDisplay)
weatherStation.setTemperature(temperature: 75) // Temperature is now: 75

In this example, the WeatherStation class is the subject, and the TemperatureDisplay class is the observer. The TemperatureDisplay instance registers itself as an observer of the WeatherStation instance, and the WeatherStation notifies all of its registered observers whenever its temperature changes by calling the update(with:) method on each observer.

Previous
Previous

Explaining State Design Pattern

Next
Next

Explaining the Singleton Design Pattern