如何解决Kotlin 扩展类如何取代装饰器设计模式?
Kotlin 的文档做出了这样的声明:
Kotlin 提供了扩展具有新功能的类的能力 无需从类继承或使用设计模式,例如 作为装饰者。
我无法理解扩展函数如何完全取代装饰器设计模式。
借用 TutorialPoint 的一个例子,你如何将下面的例子变成只使用扩展函数的代码?您能否在不牺牲对具体形状对象和装饰形状对象调用 draw()
的能力的情况下执行此操作?
interface Shape {
fun draw();
}
class Rectangle: Shape {
override fun draw() {
println("Shape: Rectangle")
}
}
class Circle: Shape {
override fun draw() {
System.out.println("Shape: Circle");
}
}
abstract class ShapeDecorator(protected val decoratedShape: Shape): Shape {
override fun draw(){
decoratedShape.draw();
}
}
class RedShapeDecorator(decoratedShape:Shape): ShapeDecorator(decoratedShape) {
override fun draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private fun setRedBorder(decoratedShape:Shape){
System.out.println("Border Color: Red");
}
}
fun main(){
val circle: Shape = Circle();
val redCircle: Shape = RedShapeDecorator(Circle());
val redRectangle: Shape = RedShapeDecorator(Rectangle());
System.out.println("Circle with normal border");
circle.draw();
System.out.println("\nCircle of red border");
redCircle.draw();
System.out.println("\nRectangle of red border");
redRectangle.draw();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。