dis*_*ard 0 design-patterns delegation kotlin
我试图理解为什么我们在 Kotlin 中具有代表功能。此示例类似于 wiki 示例https://en.wikipedia.org/wiki/Delegation_pattern
检查这个注释片段,我不需要它来在边界上使用区域函数,那么为什么我们应该使用 : ClosedShape by bounds
?
interface ClosedShape {
fun area(): Int
}
class Rectangle(val width: Int, val height: Int) : ClosedShape {
override fun area() = width * height
}
class Window(private val bounds: ClosedShape) /*: ClosedShape by bounds */ {
init {
bounds.area()
}
}
Run Code Online (Sandbox Code Playgroud)
我不需要它来在边界上使用区域函数
重点不在于能不能用area
on bounds
。当然,如果您只想打电话bounds.area()
,则不需要: ClosedShape by bounds
。
ClosedShape
这是基于和 的一些假设情况Window
,其中使用by
语法来实现接口是有帮助的。
注意 aWindow
是如何bound
被 a 编辑的Rectangle
。Window
成为 a是否有意义ClosedShape
?如果我们有一个适用于 的函数,如果我们可以直接将 a 传递给它而不是传递 ,岂不ClosedShape
是很好?Window
window.bounds
fun printArea(shape: ClosedShape) {
println(shape.area())
}
// we could write this:
printArea(window)
// rather than:
printArea(window.bounds)
Run Code Online (Sandbox Code Playgroud)
这意味着Window
将实施ClosedShape
. 我们可以在不使用委托的情况下实现它:
class Window(private val bounds: ClosedShape) : ClosedShape {
override fun area() = bounds.area()
}
Run Code Online (Sandbox Code Playgroud)
ClosedShape
但如果方法比 多得多,那将非常乏味area
。想象一下必须实现 20 个方法,所有这些方法都只调用相同的方法bounds
:
class Window(private val bounds: ClosedShape) : ClosedShape {
override fun area() = bounds.area()
override fun perimeter() = bounds.perimeter()
override fun numberOfSides() = bounds.numberOfSides()
override fun isConcave() = bounds.isConcave()
override fun contains(point: Point) = bounds.contains(point)
override fun methodWithALotOfParameters(x: Int, y: String, z: Boolean) = bounds.methodWithALotOfParameters(x, y, z)
override fun color() = bounds.color()
// and so on...
}
Run Code Online (Sandbox Code Playgroud)
您还可以想象,如果委托不是像 那样短bounds
,而是像 那样,那么这将变得多么可怕bounds.someProperty.anotherProperty
。
该by
语法消除了所有繁琐的工作,让您只需编写:
class Window(private val bounds: ClosedShape) : ClosedShape by bounds
Run Code Online (Sandbox Code Playgroud)
就是这样!您现在可以使用任何Window
作为ClosedShape
.
归档时间: |
|
查看次数: |
204 次 |
最近记录: |