interface Observer { fun update(data: Any) }
interface Subject { fun registerObserver(observer: Observer) fun removeObserver(observer: Observer) fun notifyObservers(data: Any) }
class ConcreteSubject : Subject { private val observers = mutableListOf<Observer>() private var data: Any? = null override fun registerObserver(observer: Observer) { observers.add(observer) } override fun removeObserver(observer: Observer) { observers.remove(observer) } override fun notifyObservers(data: Any) { this.data = data observers.forEach { it.update(data) } } fun setData(data: Any) { this.data = data notifyObservers(data) } }
class ConcreteObserverA : Observer { override fun update(data: Any) { println("ConcreteObserverA received data: $data") } } class ConcreteObserverB : Observer { override fun update(data: Any) { println("ConcreteObserverB received data: $data") } }
fun main() { val subject = ConcreteSubject() val observerA = ConcreteObserverA() val observerB = ConcreteObserverB() subject.registerObserver(observerA) subject.registerObserver(observerB) subject.setData("Hello, observers!") subject.removeObserver(observerA) subject.setData("Goodbye, observerA!") }
在这个例子中,我们创建了一个具体的主题类ConcreteSubject
,它维护了一个观察者列表。当主题的数据发生变化时,它会通知所有注册的观察者。我们还创建了两个具体的观察者类ConcreteObserverA
和ConcreteObserverB
,它们实现了update
方法以处理接收到的数据。
在main
函数中,我们创建了一个主题实例和两个观察者实例。我们将观察者注册到主题中,然后更改主题的数据。这将导致所有注册的观察者收到通知并处理数据。最后,我们从主题中删除一个观察者,并再次更改主题的数据,以便仅通知剩余的观察者。