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);
    }

    @Override
    public void on() {
        implementor.on();
    }

    @Override
    public 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();
    }
}

🧩 优点

  • 分离抽象与实现,减少耦合
  • 提高可扩展性,各自独立改变
  • 减少子类数量

⚠️ 缺点

  • 增加系统复杂度,结构较多
  • 初期设计需仔细分析抽象层次

✅ 使用建议

当系统在多个维度上扩展时,且希望解耦抽象和实现,避免类爆炸,使用桥接模式是理想选择。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值