You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何集中实现父接口通用属性,避免子接口重复实现?

Kotlin 集中实现父接口通用属性,避免子接口重复实现

问题场景

现有通用接口Parent,以及多个继承它的子接口AChild、BChild等。每次实现这些子接口时,都必须重复实现Parent的x属性,且所有实现逻辑完全一致。需要将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委托机制

步骤1:创建父接口的集中实现类

定义一个ParentImpl类,专门实现Parent接口的通用逻辑,把x属性的实现集中在这里:

class ParentImpl(override val x: Int) : Parent

步骤2:在子接口实现中委托父接口逻辑

实现子接口时,通过by关键字将Parent接口的实现委托给ParentImpl,这样只需要实现子接口自身的属性即可:

class ASample(value: Int) {
    val aVariable: AChild = object : AChild, Parent by ParentImpl(value) {
        override val y = value + 20
        // 无需再显式实现x属性
    }
}

class BSample(value: Int) {
    val bVariable: BChild = object : BChild, Parent by ParentImpl(value) {
        override val z = value + 10
        // 无需再显式实现x属性
    }
}

原理说明

Kotlin的委托机制允许我们将接口的实现委托给另一个对象。这里我们把Parent接口的所有成员实现都委托给ParentImpl实例,实现子接口时只需关注自身独有的成员(比如AChild的y、BChild的z),父接口的通用逻辑完全由ParentImpl维护。后续如果x的实现需要修改,只需要改动ParentImpl这一处即可。

可选优化:封装委托逻辑

如果需要进一步简化代码,可以为子接口创建通用的工厂方法,把匿名内部类的创建逻辑也集中起来:

fun createAChild(value: Int): AChild = object : AChild, Parent by ParentImpl(value) {
    override val y = value + 20
}

fun createBChild(value: Int): BChild = object : BChild, Parent by ParentImpl(value) {
    override val z = value + 10
}

// 使用示例
class ASample(value: Int) {
    val aVariable: AChild = createAChild(value)
}

class BSample(value: Int) {
    val bVariable: BChild = createBChild(value)
}

内容的提问来源于stack exchange,提问作者Navjot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 21:03:31