Motivation: When a system is partitioned into cooperating classes, a common need is to keep related objects in sync. When one object changes state, others that depend on it should be notified. The Observer design pattern implements the Publisher Subscriber Model architectural style.
Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The subject knows nothing about its observers other than through the observer interface. New observers can be added without modifying what it observes which keeps the topic and observers loosely coupled.
interface Observer {
fun update()
}
abstract class Subject {
private val observers = mutableListOf<Observer>()
fun attach(o: Observer) { observers.add(o) }
fun detach(o: Observer) { observers.remove(o) }
fun notify() { observers.forEach { it.update() } }
}
class ConcreteSubject : Subject() {
private var state: Int = 0
fun getState(): Int = state
fun setState(value: Int) {
state = value
notify()
}
}
class ConcreteObserver(private val subject: ConcreteSubject) : Observer {
override fun update() {
val state = subject.getState()
// react to state change...
}
}