Kotlin學習之-5.12 代理模式
類代理
代理模式已經被證明是一種很好的替代實現繼承的方式,並且Kotlin原生支持代理模式還不需要任何多餘代碼。一個類Derived
可以從一個接口Base
繼承並且代理所有他的共有方法到一個特定的對象上。
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).print() // 輸出10
}
在Derived
類的父類列表中的by
語句表明b
會被存儲在Derived
對象的內部,然後編譯器會參照所有Base
的方法在b
中生成一次。
注意,複寫方法會和你預期的一致。編譯器會使用你複寫override
的實現而不是在代理對象中的實現。如果我們添加override fun print() { print("abc") }
到Derived
類中,那麼程序將會輸出”abc” 而不是”10”。
PS,我會堅持把這個系列寫完,有問題可以留言交流,也關注專欄Kotlin for Android Kotlin安卓開發