Sobes.tech
Junior — Middle

Can you explain how the Observer pattern works and in what cases it is used?

sobes.tech AI

Answer from AI

The Observer pattern allows an object (the publisher) to notify other objects (subscribers) about changes in its state without a tight coupling between them. The publisher maintains a list of subscribers and notifies them upon changes.

This pattern is often used to implement event systems, for example, in iOS — NotificationCenter, KVO (Key-Value Observing), or delegates.

Example in Swift:

protocol Observer: AnyObject {
    func update(value: Int)
}

class Subject {
    private var observers = [Observer]()
    private var value: Int = 0 {
        didSet {
            notify()
        }
    }
    
    func addObserver(_ observer: Observer) {
        observers.append(observer)
    }
    
    func setValue(_ newValue: Int) {
        value = newValue
    }
    
    private func notify() {
        observers.forEach { $0.update(value: value) }
    }
}

class ConcreteObserver: Observer {
    func update(value: Int) {
        print("Value updated to \(value)")
    }
}

let subject = Subject()
let observer = ConcreteObserver()
subject.addObserver(observer)
subject.setValue(10)  // Will output: Value updated to 10

Used when it is necessary to separate the data source from consumers and ensure flexible subscription to events.

Can you explain how the Observer pattern works and in… - sobes.tech