首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 橋接模式(Bridge Pattern)深度解析與程式碼示例

     編輯:Java 相關知識

模式動機:分離抽象與實作

橋接模式將抽象部分(Abstraction)與其實作部分(Implementation)解耦,使兩者可以獨立變化。核心在於「組合大於繼承」,避免多維度變化導致的類別組合爆炸。

角色結構

  • Abstraction(抽象化):定義高層介面,持有 Implementor 引用。
  • RefinedAbstraction(修正抽象化):擴充抽象介面。
  • Implementor(實作化介面):定義底層操作介面。
  • ConcreteImplementor(具體實作化):實作 Implementor 介面。

經典範例:形狀與繪圖器分離

形狀(圓形、正方形)為抽象維度;繪圖器(彩色、黑白)為實作維度。兩者正交變化,橋接模式完美契合。

1. 實作化介面

interface Printer {
    void print(int radius, int x, int y);
}

2. 具體實作化

class ColorPrinter implements Printer {
    @Override public void print(int radius, int x, int y) {
        System.out.println("Color: radius=" + radius + ", x=" + x + ", y=" + y);
    }
}
class BlackPrinter implements Printer {
    @Override public void print(int radius, int x, int y) {
        System.out.println("Black: radius=" + radius + ", x=" + x + ", y=" + y);
    }
}

3. 抽象化基類

abstract class Shape {
    protected Printer printer; // 橋接引用
    protected Shape(Printer p) { this.printer = p; }
    public abstract void draw();
}

4. 修正抽象化:圓形

class Circle extends Shape {
    private int x, y, radius;
    public Circle(int x, int y, int radius, Printer drawer) {
        super(drawer);
        this.x = x; this.y = y; this.radius = radius;
    }
    @Override public void draw() {
        printer.print(radius, x, y); // 委派給實作化
    }
}

5. 客戶端驗證

public class Main {
    public static void main(String[] args) {
        Shape redCircle = new Circle(100, 100, 10, new ColorPrinter());
        Shape blackCircle = new Circle(100, 100, 10, new BlackPrinter());
        redCircle.draw();   // 輸出 Color 版本
        blackCircle.draw(); // 輸出 Black 版本
    }
}

橋接 vs 策略模式

兩者結構相似,但意圖不同:

  • 橋接:結構型,關注永久性的維度分離(如平台與業務、介面與資料庫驅動)。
  • 策略:行為型,關注可互換的演算法/行為(如排序策略、支付策略)。

實戰應用場景

  • JDBC 驅動架構:Connection(抽象)+ 各廠商 Driver(實作)。
  • 跨平台 GUI:視窗抽象 + Windows/Linux/Mac 具體繪製。
  • 訊息推送:通知抽象(簡訊、Email、Push)+ 不同廠商通道實作。

優缺點權衡

優點缺點
抽象與實作獨立擴充,符合開放封閉原則增加系統理解複雜度,需識別正交維度
隱藏實作細節,客戶端只依賴抽象不適用於維度高度耦合、難以分離的場景
減少子類別數量,避免繼承爆炸雙重間接呼叫略增效能開銷(可忽略)

總結

橋接模式是處理「多維度變化」的利器。關鍵在於識別出系統中穩定的抽象介面與易變的實作維度,透過組合橋接實現雙向獨立演進。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved