Sobes.tech
Junior — Middle

How does the Observer pattern notify registered objects about changes?

sobes.tech AI

Answer from AI

The Observer pattern implements a subscription mechanism where one object (Subject) maintains a list of observers (Observers) and notifies them of any changes to its state.

When the state of the Subject changes, it calls a notification method (e.g., notifyObservers), which iterates through all registered observers and calls their update method. This way, all subscribers receive the latest information and can react to changes.

Example in Kotlin for Android:

interface Observer {
    fun update(data: String)
}

class Subject {
    private val observers = mutableListOf<Observer>()
    private var state: String = ""

    fun registerObserver(observer: Observer) {
        observers.add(observer)
    }

    fun unregisterObserver(observer: Observer) {
        observers.remove(observer)
    }

    fun setState(newState: String) {
        state = newState
        notifyObservers()
    }

    private fun notifyObservers() {
        for (observer in observers) {
            observer.update(state)
        }
    }
}

Thus, the pattern ensures loose coupling between objects and is suitable for event-driven systems.