目录

结构型:装饰器模式

释义

装饰器模式,在原来的基础上再加一点点。

/%E7%BB%93%E6%9E%84%E5%9E%8B%E8%A3%85%E9%A5%B0%E5%99%A8%E6%A8%A1%E5%BC%8F/%E7%BB%93%E6%9E%84%E5%9E%8B%EF%BC%9A%E8%A3%85%E9%A5%B0%E5%99%A8%E6%A8%A1%E5%BC%8F.resources/A1B93B6E-A468-438B-8366-C827ACE0AE17.png
装饰器模式
Circle和抽象装饰器Decorator都实现了图形Shape接口。圆Circledraw()只能画出圆,我们可以用红色装饰器RedDecorator来为图形涂上红色:RedDecoratordraw()会在调用圆Shapedraw()的基础上再添加涂成红色的方法。

图形

1
2
3
interface Shape {
    fun draw()
}

1
2
3
4
5
class Circle {
    override fun draw() {
        drawCircle()
    }
}

装饰器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
abstract class Decorator(val shape: Shape): Shape {
    override fun draw() {
        shape.draw()
    }
}

class RedDecorator(shape: Shape): Shape(shape) { // Shape都可以
    override fun draw() {
        shape.draw() // 调用Shape的方法来画出图形
        drawRed(shape) // 把图形“装饰”成红色
    }
    
    // 涂成红色
    override fun drawRed() {
        ...
    }
}

使用

1
2
3
4
5
6
fun main() {
    val circle: Circle = Circle()
    // 被涂成红色的圆形
    val redCircle: Decorator = RedDecorator(circle)
    redCircle.draw() // 会调用RedDecorator中的draw()
}