我已经遍历了关于委托模式的多个链接(One,Two)和documentation,并从某种程度上理解了它以“ composition over继承”。我可以看到内置的委托属性(惰性,否决,地图,可观察)如何有用;但是很难理解两个领域:
1。为什么/何时应该为属性编写自定义委托?比覆盖该属性的获取方法/方法更好?
比较两种方法:
private var withoutDelegate: String = ""
get() = DataHelper.getLatestData(::withoutDelegate.name)
set(value) {
DataHelper.setLatestData(value)
field = value
}
val withDelegate by StringDelegateProvider()
class StringDelegateProvider {
operator fun getValue(thisRef: String?, property: KProperty<*>): String {
return DataHelper.getLatestData(property.name)
}
}
2。在班级,委派比传统的写作方式更好吗?
比较这两种方法-无需委派的组合似乎更为简洁:
interface Base {
fun print()
}
class BaseImpl1(val x: Int) : Base {
override fun print() { print(x) }
}
class BaseImpl2(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
fun clientFunctionWithDelegation() {
val i1 = BaseImpl1(10)
val i2 = BaseImpl2(10)
val b1 = Derived(i1)
val b2 = Derived(i2)
b1.print()
b2.print()
}
fun clientFunctionWithoutDelegation(){
//wihtout extending Base, we can still create multiple types of Base and use them conditionally.
val i1: Base = BaseImpl1(10)
val i2: Base = BaseImpl2(10)
i1.print()
i2.print()
}
希望社区能够共享一些委派可以提供帮助的用例。
答案 0 :(得分:0)
1:您可以重用委托,而不必每次都覆盖get
和/或set
。范例:lazy
代表
2:假设您要创建一个MutableList
,以便在每次更改列表时打印该列表。您不想重新实现MutableList
,只想覆盖使列表发生变化的函数。因此,您无需手动委派每个呼叫,只需说class PrintList<T>(original: MutableList<T>) by original
,然后覆盖您关心的功能