Kotlin's documentation makes this statement:
Kotlin provides an ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator.
I am having trouble understanding how extension functions can completely replace the decorator design pattern.
To borrow an example from TutorialPoint how would you turn the below example into code that only used extension functions? Can you do this without sacrificing the ability to call draw()
on both concrete shape objects and decorated shape objects?
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();
}
Aucun commentaire:
Enregistrer un commentaire