Kotlin委托Delegate托管by
import kotlin.reflect.KPropertyfun main() {var user: String by MyDelegate()user = "fly"println(user)
}class MyDelegate {private var v: String? = nulloperator fun getValue(thisRef: Any?, property: KProperty<*>): String {return "property='${property.name}' getValue ${v}"}operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {v = valueprintln("property='${property.name}' setValue -> $value")}
}
property='user' setValue -> fly
property='user' getValue fly
import kotlin.properties.*fun main() {var len: Int by Delegates.observable(0) { prop, oldValue, newValue ->println("$oldValue -> $newValue")}len = 2023len = 2024
}
0 -> 2023
2023 -> 2024
Delegates.observable追踪观察可变数据更新,Kotlin_zhangphil的博客-CSDN博客**Java观察者模式的场景:一个女孩洗澡,被很多男孩偷看。女孩洞察后,搜索坏男孩,然后继续洗澡。*//*男孩Boy.java*/import java.util.Observable;不定长函参的Java观察者模式更新数据传递import java.util.LinkedList;/** * 抽象被观察者。Java观察者模式 : Observer / Observable_zhangphil的博客-CSDN博客。不定长函参的Java观察者模式更新数据传递_zhangphil的博客-CSDN博客。https://blog.csdn.net/zhangphil/article/details/132088085