Kotlin 扩展类如何取代装饰器设计模式?

问题描述

Kotlin 的文档做出了这样的声明:

Kotlin 提供了扩展具有新功能的类的能力 无需从类继承或使用设计模式,例如 作为装饰者。

Kotlin Extensions

我无法理解扩展函数如何完全取代装饰器设计模式。

借用 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();
}

TutorialPoint Example in Java

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)