我有以下接口和两个类:
interface A {
fun foo()
fun bar()
}
class B {
fun foo() {}
}
class C {
fun bar() {}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能以某种方式使用/组合这两个类来为此接口提供实现?
在不更改给定代码的情况下执行此操作的一种方法是仅使用B和C在新类中实现的实例A:
class D : A {
private val b = B()
private val c = C()
override fun foo() = b.foo()
override fun bar() = c.bar()
}
Run Code Online (Sandbox Code Playgroud)
但是,这不能很好地扩展,并且需要编写样板。使用 Kotlin,您可以通过委托来实现接口,这基本上与上述完全相同,但是是自动的。但是,这需要您将接口拆分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()
Run Code Online (Sandbox Code Playgroud)
如果需要Band 的C可配置实例,可以通过其构造函数将它们传递给 D:
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()
Run Code Online (Sandbox Code Playgroud)
如果B和/或C具有带参数的构造函数,您可以从的构造函数创建B和/或C使用参数的实例D:
class D(val b: B, val c: C): A, Foo by b, Bar by c
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44 次 |
| 最近记录: |