我有以下接口(interface)和两个类:
interface A {
fun foo()
fun bar()
}
class B {
fun foo() {}
}
class C {
fun bar() {}
}
是否有可能以某种方式使用/组合这 2 个类为此接口(interface)提供实现?
最佳答案
在不更改给定代码的情况下执行此操作的一种方法是在实现 A
的新类中仅使用 B
和 C
的实例:
class D : A {
private val b = B()
private val c = C()
override fun foo() = b.foo()
override fun bar() = c.bar()
}
但这并不能很好地扩展,并且需要编写样板文件。
使用 Kotlin,您可以通过委托(delegate)实现接口(interface),这基本上完全按照上述方式执行,但是是自动的。
但是,这需要您将接口(interface) A
拆分为由 B
实现的部分和由 C
实现的部分:
interface Foo {
fun foo()
}
interface Bar {
fun bar()
}
interface A : Foo, Bar
class B : Foo {
override fun foo() {}
}
class C : Bar {
override fun bar() {}
}
class D : A, Foo by B(), Bar by C()
如果您需要 B
和 C
的可配置实例,您可以通过其构造函数将它们传递给 D:
class D(val b: B, val c: C): A, Foo by b, Bar by c
如果 B
和/或 C
具有带参数的构造函数,您可以创建 B
和/或 C
使用 D
的构造函数中的参数:
class B(val something: String) : Foo { ... }
class D(something: String) : A, Foo by B(something), Bar by C()
关于kotlin - 如何使用两个组合类提供接口(interface)实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67967175/