父接口的公共属性如何实现?

问题描述 投票:0回答:1

我想在单个中心位置的父界面中实现常见功能。我有:

  • 通用接口:
    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
        }
    }
kotlin oop inheritance interface
1个回答
0
投票

为了使父接口实现仅在中心位置执行一次,您可以按如下方式创建委托:

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.