官方文檔: 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所有方法/函數(shù)
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.reibang.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