Design Pattern

Chapter 7 橋接模式(Bridge Pattern)

定義

將抽象部分與它的實現部分分離,使它們都可以獨立地變化。

組成

  1. 抽象類(Abstraction):定義了抽象部分的接口,操作一個實現部分對象的引用。
  2. 擴充抽象類(RefinedAbstraction):繼承自抽象部分的類。
  3. 實現類接口(Implementor):實現部分的接口。
  4. 具體實現類(ConcreteImplementor):實現了Implementor定義的接口的具體類。

程式碼

Step1

public interface DrawAPI {
    public void drawCircle(int radius, int x, int y);
}

Step2

public class RedCircle implements DrawAPI{
    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("畫個圓[ 顏色: 紅色, radius: " + radius + ", x: " + x + ", " + y + "]");
    }
}


public class GreenCircle implements DrawAPI{
    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("畫個圓[ 顏色: 綠色, radius: " + radius + ", x: " + x + ", " + y + "]");
    }
}

Step3

public abstract class Shape {
    protected DrawAPI drawAPI;
    protected Shape(DrawAPI drawAPI){
        this.drawAPI = drawAPI;
    }
    public abstract void draw();
}

Step4

public class Circle extends Shape{
    private int x, y, radius;
    protected Circle(int x, int y, int radius, DrawAPI drawAPI) {
        super(drawAPI);
        this.x = x;  
        this.y = y;  
        this.radius = radius;
    }

    @Override
    public void draw() {
        drawAPI.drawCircle(radius,x,y);        
    }
}

Step5

public class BridgePatternDemo {
    public static void main(String[] args) {
        Shape redCircle = new Circle(100,100, 10, new RedCircle());
        Shape greenCircle = new Circle(100,100, 10, new GreenCircle());

        redCircle.draw();
        greenCircle.draw();
    }
}

Step6(Output)

畫個圓[ 顏色: 紅色, radius: 10, x: 100, 100]
畫個圓[ 顏色: 綠色, radius: 10, x: 100, 100]

優點

  1. 抽象和實現的分離。
  2. 橋接模式提高了系統的可擴充性,在兩個變化維度中任意擴展一個維度,都不需要修改原有系統。
  3. 實現細節對客戶透明,可以對用戶隱藏實現細節。

缺點

  1. 橋接模式的引入會增加系統的理解與設計難度,由於聚合關聯關係建立在抽象層,要求開發者針對抽象進行設計與編程。