在 Kotlin 中,觀察者模式可以通過定義一個主題(Subject)類和一個或多個觀察者(Observer)接口來實現(xiàn)。以下是一個簡單的示例:
Observer
:interface Observer {
fun update(data: String)
}
Subject
,它包含一個觀察者列表和一個方法來添加、刪除觀察者以及通知所有觀察者:class Subject {
private val observers = mutableListOf<Observer>()
fun addObserver(observer: Observer) {
observers.add(observer)
}
fun removeObserver(observer: Observer) {
observers.remove(observer)
}
fun notifyObservers(data: String) {
observers.forEach { it.update(data) }
}
}
ConcreteObserver
,實現(xiàn) Observer
接口:class ConcreteObserver : Observer {
override fun update(data: String) {
println("Observer received data: $data")
}
}
fun main() {
val subject = Subject()
val observerA = ConcreteObserver()
val observerB = ConcreteObserver()
subject.addObserver(observerA)
subject.addObserver(observerB)
subject.notifyObservers("Hello, Observer Pattern!")
}
運行上述代碼,將看到以下輸出:
Observer received data: Hello, Observer Pattern!
Observer received data: Hello, Observer Pattern!
這就是 Kotlin 中實現(xiàn)觀察者模式的基本方法。你可以根據(jù)實際需求對這個示例進(jìn)行修改和擴展。