Java 橋接模式(Bridge Pattern)詳解
🌉 什么是橋接模式?
橋接模式用于將抽象部分與實現部分分離,使它們可以獨立變化。
通過在兩個獨立變化的維度之間建立“橋”,避免因多維度擴展導致的類爆炸。
🧠 使用場景
- 系統需要在多個維度進行擴展
- 想解耦抽象和實現,讓它們各自獨立發展
- 減少子類的數量,避免類爆炸
🏗? 模式結構
- Abstraction(抽象類):定義高層接口,持有 Implementor 引用
- RefinedAbstraction(擴充抽象類):擴展抽象定義
- Implementor(實現接口):定義底層實現接口
- ConcreteImplementor(具體實現):提供具體實現
? 示例:不同品牌的電視遠程控制
實現接口(Implementor)
public interface TV {void on();void off();void tuneChannel(int channel);
}
具體實現(ConcreteImplementor)
public class SonyTV implements TV {public void on() { System.out.println("Sony TV is ON"); }public void off() { System.out.println("Sony TV is OFF"); }public void tuneChannel(int channel) { System.out.println("Sony TV tuned to channel " + channel); }
}public class SamsungTV implements TV {public void on() { System.out.println("Samsung TV is ON"); }public void off() { System.out.println("Samsung TV is OFF"); }public void tuneChannel(int channel) { System.out.println("Samsung TV tuned to channel " + channel); }
}
抽象類(Abstraction)
public abstract class RemoteControl {protected TV implementor;public RemoteControl(TV implementor) { this.implementor = implementor; }public abstract void on();public abstract void off();
}
擴充抽象類(RefinedAbstraction)
public class AdvancedRemoteControl extends RemoteControl {public AdvancedRemoteControl(TV implementor) {super(implementor);}@Overridepublic void on() {implementor.on();}@Overridepublic void off() {implementor.off();}public void setChannel(int channel) {implementor.tuneChannel(channel);}
}
客戶端調用
public class Client {public static void main(String[] args) {TV sony = new SonyTV();RemoteControl remote = new AdvancedRemoteControl(sony);remote.on();((AdvancedRemoteControl) remote).setChannel(5);remote.off();TV samsung = new SamsungTV();remote = new AdvancedRemoteControl(samsung);remote.on();((AdvancedRemoteControl) remote).setChannel(10);remote.off();}
}
🧩 優點
- 分離抽象與實現,減少耦合
- 提高可擴展性,各自獨立改變
- 減少子類數量
?? 缺點
- 增加系統復雜度,結構較多
- 初期設計需仔細分析抽象層次
? 使用建議
當系統在多個維度上擴展時,且希望解耦抽象和實現,避免類爆炸,使用橋接模式是理想選擇。