天天看點

Kotlin-19.代理/委托類(Delegation)

官方文檔: http://kotlinlang.org/docs/reference/delegation.html

類代理/委托(Class Delegation)

代理/委托模式(Delegation pattern)已被證明是替代繼承的一個很好方式,
而Kotlin原生支援它:    
    interface Base {
        fun p1()
        fun p2()
    }

    class Impl() : Base {
        override fun p1() {
            println("p1_Impl")
        }
        override fun p2() {
            println("p2_Impl")
        }
    }

    //by base表示 Deg會存儲base,代理Base所有方法/函數
    class Deg(base: Base) : Base by base{
        override fun p2() {
            println("p2_Deg")
        }
    }

    fun main(args: Array<String>) {
        val deg = Deg(Impl())
        deg.p1() //輸出p1_Impl
        deg.p2() //輸出p2_Deg
    }
           

簡書:http://www.jianshu.com/p/75177a9e91b7

CSDN部落格: http://blog.csdn.net/qq_32115439/article/details/73718749

GitHub部落格:http://lioil.win/2017/06/25/Kotlin-delegation.html

Coding部落格:http://c.lioil.win/2017/06/25/Kotlin-delegation.html