代理是什么
接口代理:對象x代替當前類a實現接口b*的方法
*屬性代理:對象x代替屬性a實現getter/setter方法,lazy就是一個屬性代理
舉例說明
interface Api {
fun method1()
fun method2()
fun method3()
}
class ApiTest : Api{
override fun method1() {
Log.i("shawn","ApiTest=method1")
}
override fun method2() {
Log.i("shawn","ApiTest=method2")
}
override fun method3() {
Log.i("shawn","ApiTest=method3")
}
}
/**
* 對象api代替ApiWrapper實現接口Api
* */
class ApiWrapper(api:Api) : Api by api{
override fun method1() {
Log.i("shawn","ApiWrapper=method1")
}
}
調用:val a:ApiTest = ApiTest()
val b:ApiWrapper = ApiWrapper(a)
b.method1()
b.method2()
輸出結果:ApiWrapper=method1
ApiTest=method2
屬性代理Setter/Getter
val name: String by lazy {
name1.split(" ")[0]
}
var state:Int by Delegates.observable(100){
property, oldValue, newValue ->
Log.i("shawn", "oldValue=${oldValue},newValue=$newValue")
}