橋接模式的英文是 Bridge,其核心意圖是將抽象部分與實現部分分離,使它們可以獨立變化。傳統繼承方式在面對多維度變化時會導致類爆炸,橋接模式通過組合關係替代繼承,將抽象與實現解耦,極大提升系統擴展性。
假設有 2 種水果(蘋果、橘子)和 2 類人(男人、女人),人吃水果共有 2×2=4 種組合。若用繼承實現,需建立 4 個類;若水果增加到 10 種、人增加到 5 類,則需 50 個類。橋接模式只需 10+5=15 個類,優勢顯而易見。

package com.brucezhang.bridge;
public abstract class Fruit {
// 抽象方法:吃水果,參數為人
public abstract void eatFruit(People people);
}
public class Apple extends Fruit {
@Override
public void eatFruit(People people) {
System.out.println(people.getType() + " eat apple !");
}
}
public class Oranger extends Fruit {
@Override
public void eatFruit(People people) {
System.out.println(people.getType() + " eat oranger !");
}
}
public abstract class People {
private String type;
private Fruit fruit;
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public Fruit getFruit() { return fruit; }
public void setFruit(Fruit fruit) { this.fruit = fruit; }
// 抽象方法:吃
public abstract void eat();
}
public class Man extends People {
public Man() { setType("Man"); }
@Override
public void eat() {
getFruit().eatFruit(this); // 委派給實現層
}
}
public class Woman extends People {
public Woman() { setType("Woman"); }
@Override
public void eat() {
getFruit().eatFruit(this);
}
}
public class Main_Test {
public static void main(String[] args) {
People man = new Man();
People woman = new Woman();
Fruit apple = new Apple();
Fruit oranger = new Oranger();
// 動態組合:任意人吃任意水果
apple.eatFruit(man);
oranger.eatFruit(woman);
apple.eatFruit(woman);
oranger.eatFruit(man);
}
}
Man eat apple !
Woman eat oranger !
Woman eat apple !
Man eat oranger !
橋接模式常用於 JDBC 驅動、集合框架、消息推送等多維度變化的場景,是掌握「組合優於繼承」原則的經典實踐。