3.接口代理

接口方法交给代理类实现 关键字 by

interface Driver{
    fun drive()
}

interface Writer{
    fun write()
}
class CarDriver: Driver {
    override fun drive() {
        println("开车呢")
    }
}

class PPTWriter: Writer {
    override fun write() {
        println("做PPT呢")
    }
}

class SeniorManager(val driver: Driver, val writer: Writer): Driver, Writer{
    override fun drive() {
        driver.drive()
    }
    override fun write() {
        writer.write()
    }
}

fun main(args: Array) {
    val driver = CarDriver()
    val writer = PPTWriter()
    val seniorManager = SeniorManager(driver, writer)
    seniorManager.drive()
    seniorManager.write()
}

其中用kotlin接口代理,SeniorManager可以这样写

class SeniorManager(val driver: Driver, val writer: Writer): Driver by driver, Writer by writer

你可能感兴趣的:(3.接口代理)