目录

结构型:外观模式

释义

外观模式,隐藏内部逻辑的复杂性,仅提供接口供客户端访问,这些接口就是“外观”。

/%E7%BB%93%E6%9E%84%E5%9E%8B%E5%A4%96%E8%A7%82%E6%A8%A1%E5%BC%8F/%E7%BB%93%E6%9E%84%E5%9E%8B%EF%BC%9A%E5%A4%96%E8%A7%82%E6%A8%A1%E5%BC%8F.resources/DC7A37C5-A999-4220-85B9-D8067AA9E13D.png
外观模式
ShapeMaker是为客户端提供的接口,CircleSquare接入Shape。客户端通过ShapeMaker中的各种接口在ShapeMaker中创建Shape的各种实例并调用实例的方法。

基础类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
interface Shape {
    fun draw()
}

class Circle : Shape {
    override fun draw() {
        drawCircle()
    }
}

class Square : Shape {
    override fun draw() {
        drawSquare()
    }
}

接口

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class ShapeMaker( 
    // 包含的Shape类
    private var circle : Circle
    private var square : Square
) {
    // 向客户端提供接口
    public fun drawCircle() {
        circle.draw()
    }
    
    public fun drawSquare() {
        square.draw()
    }
}

使用

1
2
3
4
5
6
7
8
9
fun main() {
    val circle: Circle = Circle()
    val square: Square = Square()
    
    val shapeMaker: ShapeMaker = ShapeMaker(circle, square)
    // 调用接口
    shapeMaker.drawCircle()
    shapeMaker.drawSqaure()
}