代理接口

例子1

Api 接口有3个函数

  1. interface Api {
  2. fun eat()
  3. fun drink()
  4. fun play()
  5. }

ApiImpl 实现接口,并打印内容

class ApiImpl : Api {
    override fun eat() {
        println("ApiImpl 吃吃吃")
    }

    override fun drink() {
        println("ApiImpl 喝喝喝")
    }

    override fun play() {
        println("ApiImpl 玩玩玩")
    }
}

增强API接口类

class ApiWrapper(val api: Api) : Api {
    override fun eat() {
        api.eat()
    }

    override fun drink() {
        api.drink()
    }

    override fun play() {
        api.play()
    }

    fun getMoney(){
        println("ApiWrapper 取钱")
    }
}
  • override 方法必须自己去调用api.xxx实现,有没有更便捷的方法呢?

通过 by 代理实现接口

class ApiWrapperDelegate(val api: Api) : Api by api {
    fun getMoney(){
        println("ApiWrapperDelegate 取钱")
    }
}
  • //对象var api 代替 ApiWrapperDelegate 去实现 Api

调用实例

fun main() {
    val apiImpl = ApiImpl()
    ApiWrapper(apiImpl).drink()
    ApiWrapperDelegate(apiImpl).drink()
}
ApiImpl 喝喝喝
ApiImpl 喝喝喝

例子2

新建一个增强List类,实现MutableList需要重写很多方法

class SuperList<E>(
        val list: MutableList<E?> = ArrayList()
) : MutableList<E?> {
    override val size: Int
        get() = TODO("Not yet implemented")

    override fun contains(element: E?): Boolean {
        TODO("Not yet implemented")
    }

    override fun containsAll(elements: Collection<E?>): Boolean {
        TODO("Not yet implemented")
    }

    ...略

}

但是如果使用代理就非常简单了

class SuperList<E>(
        val list: MutableList<E?> = ArrayList()
) : MutableList<E?> by list{

    fun listTimes( times:Int):Int{
      return list.size*times
    }
}

属性代理

例子1

class Person(var name: String) {

    val firstName by lazy {
        name.split(" ")[0]
    }
}

fun main() {
    val person = Person("John Wick")
    println(person.firstName)
}
  • lazy 接口实例 代理了属性 firstName 的 getter