# 委托
## 類委托
[委托模式](https://en.wikipedia.org/wiki/Delegation_pattern)已經被證明是實現繼承的一個很好的替代選擇,Kotlin 原生零樣本代碼的支持它。類 `Derived` 可以從接口 `Base` 繼承并委托它所有的 public 方法給指定的對象:
``` kotlin
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
fun main() {
val b = BaseImpl(10)
Derived(b).print() // 打印 10
}
```
`Derived` 超類列表中的 `by` 分支指明 `b` 將存儲在 `Derived` 的對象內部并且編譯器將生成 `Base` 的所有方法附帶給 `b`。