23种设计模式-结构型模式之桥接模式(Java版本)
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();}
}
🧩 优点
- 分离抽象与实现,减少耦合
- 提高可扩展性,各自独立改变
- 减少子类数量
⚠️ 缺点
- 增加系统复杂度,结构较多
- 初期设计需仔细分析抽象层次
✅ 使用建议
当系统在多个维度上扩展时,且希望解耦抽象和实现,避免类爆炸,使用桥接模式是理想选择。