Kotlin 进阶 学习 委托

1.接口委托

package com.jmj.jetpackcomposecompositionlocal.byStudy
/**
 * 接口委托
 */
interface HomeDao{
    fun getAllData():List}
interface ADao{
        fun getById(id:Int):String
}
class HomeDaoImpl:HomeDao{
    override fun getAllData(): List {
        return listOf("home")
    }
}
class ADaoImpl:ADao{
    override fun getById(id: Int): String {
        return "object id = $id"
    }
}
//这里多态也可以
class HomeService(homeDaoImpl: HomeDaoImpl,aDao: ADao):HomeDao by homeDaoImpl,ADao by aDao{
    fun getRedisData():String{
        return "redis"
    }
}
fun main() {
    val homeService = HomeService(HomeDaoImpl(),ADaoImpl())
    val allData = homeService.getAllData()
    println(allData)
    println(homeService.getById(3))
}

2.属性委托

package com.jmj.jetpackcomposecompositionlocal.byStudy
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun main() {
    var test:String  by MyTestClass()
    test="123"
    println(test)
}

//如果是只读变量 委托 就实现 ReadOnlyProperty 接口
//<第一个类型是我们属性所属的那个类,第二个类型是我们属性本身的类型>class MyTestClass:ReadWriteProperty{
    private  var myVar = ""
    override fun getValue(thisRef: Nothing?, property: KProperty<*>): String {
        println("调用了get方法")
        return myVar
    }
    override fun setValue(thisRef: Nothing?, property: KProperty<*>, value: String) {
        println("调用了set方法")
       myVar = value
    }
}
package com.jmj.jetpackcomposecompositionlocal.byStudy
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun main() {
   A().apply {
      this.aTest = "hello"
       println(aTest)
   }
}
class A{
    var aTest:String by MyTestClass()
}
class B{
    var aTest:String by MyTestClass()
}
//如果是只读变量 委托 就实现 ReadOnlyProperty 接口
//<第一个类型是我们属性所属的那个类,第二个类型是我们属性本身的类型>class MyTestClass:ReadWriteProperty{
    private  var myVar = ""
    override fun getValue(thisRef: Any, property: KProperty<*>): String {
        return myVar
    }
    override fun setValue(thisRef: Any, property: KProperty<*>, value: String) {
        myVar =value
    }
}

3.延迟委托

package com.jmj.jetpackcomposecompositionlocal.byStudy
fun main() {
    val test by lazy{
        println("初始化了test")
        "hello"
    }
    
    println(test)
}

4.监听委托

package com.jmj.jetpackcomposecompositionlocal.byStudy
import kotlin.properties.Delegates
fun main() {
    var test by Delegates.observable("hello"){_, oldValue, newValue -> println("oldValue $oldValue")
        println("newValue $newValue")
    }
    test = "TEAt"
    test = "TEAt"
    test = "TEAt"
    println(test)
    println(test)
    println(test)
    println(test)
    println(test)
}

 实际上还是实现了ReadWriteProperty这个接口来实现监听委托

Jetpack compose 里的状态 也是 委托实现 重构 compose。

就是 Mutable 返回一个 状态对象 这个对象里的属性 被另一个类委托了,这个属性调用了 set方法

就会委托去调用委托类的set方法,然后在那个实现方法里去实现compose组件重构,完成页面渲染。