Bridge Pattern(橋接模式)
把抽象類與實現類解耦,讓二者可以獨立變化,這種模式會讓一個interface作為橋接的接口,讓實體類的功能與接口類的功能能獨立完成且互不影響
好處
可以讓抽象類和實現類分離並且方便未來擴展,來達到解耦的效果
程式範例
建立 Bridge 的設計模式有幾個要注意的地方
這邊把接口先命名為DrawAPI比較好理解
1.先創建一個DrawAPI作為抽象類與實現類的接口
2.把創建好的DrawAPI當作參數傳給抽象類,並寫出抽象方法,這樣之後都可以調用方法來同步執行
3.實現抽象類並複寫抽象方法,之後調用DrawAPI的方法把參數都反回給DrawAPI,讓之後調用的人不用清楚內部構造只要給特定參數就能得到物件
4.所有想要調用的類,都要實現DrawAPI裡面的方法
橋接接口
interface DrawAPI {
    fun drawCircle(x: Int, y: Int, radius: Int)
    fun drawSquare(x: Int, y: Int)
}
抽象類
abstract class Shape(drawAPI: DrawAPI) {
    abstract fun draw()
}
實現抽象類
class Square(val x: Int, val y: Int, val drawAPI: DrawAPI) : Shape(drawAPI) {
    override fun draw() {
        drawAPI.drawSquare(x,y)
    }
}
class Circle(val x: Int, val y: Int, val radius: Int, val drawAPI: DrawAPI) : Shape(drawAPI) {
    override fun draw() {
        drawAPI.drawCircle(x,y,radius)
    }
}
一般類別
class Yellow : DrawAPI {
    override fun drawCircle(x: Int, y: Int, radius: Int) {
        println("Draw Circle Yellow radius:{radius}  x:{x} y:{y}")
    }
    override fun drawSquare(x: Int, y: Int) {
        println("Draw Square Yellow x:{x} y:${y}")
    }
}
執行結果
fun main() {
    val yellowSquare = Square(100,50, Yellow())
    val yellowCircle = Circle(100,50, 50, Yellow())
    yellowSquare.draw()
    yellowCircle.draw()
}
Draw Square Yellow x:100 y:50
Draw Circle Yellow radius:50  x:100 y:50