我想在单个中心位置的父界面中实现常见功能。我有:
Parent
AChild, BChild...
每当我尝试实现任何这些子接口时,我发现自己每次都必须实现父接口 (
Parent
) 的属性,并且整个代码库的实现都是相同的。
假设父接口实现仅在中心位置完成一次,如何在不显式实现父接口(
AChild, BChild...
)的情况下获得子接口(Parent
)的实现?
interface Parent {
val x: Int
}
interface AChild : Parent {
val y: Int
}
interface BChild : Parent {
val z: Int
}
class ASample(value: Int) {
val aVariable: AChild = object : AChild {
override val y = value + 20
override val x = value
}
}
class BSample(value: Int) {
val bVariable: BChild = object : BChild {
override val z = value + 10
override val x = value
}
}
为了使父接口实现仅在中心位置执行一次,您可以按如下方式创建委托:
class ParentDelegate(value: Int) : Parent {
override val x: Int = value
}
然后在子接口的实现中使用它:
class ASample(value: Int) {
val aVariable: AChild = object : AChild, Parent by ParentDelegate(value) {
override val y: Int = value + 20
}
}
class BSample(value: Int) {
val bVariable: BChild = object : BChild, Parent by ParentDelegate(value) {
override val z = value + 10
}
}