代理是什么
接口代理:对象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")
}
网友评论