设计模式-桥接模式

桥接模式UML类图:

桥接模式通常包含以下角色:

  • 抽象类(Abstraction):定义了抽象类的接口,维护一个指向实现对象的引用。
  • 扩展抽象类(RefinedAbstraction):扩展抽象类,实现抽象类中的业务逻辑,可以覆盖或扩展抽象类的方法。
  • 实现接口(Implementor):定义了实现类的接口,不继承抽象类。实现所有与抽象类相关的操作,这些操作定义在抽象类中。
  • 具体实现类(ConcreteImplementor):实现实现接口的具体类,提供具体的实现代码。

一、实现接口(Implementor)

java 复制代码
public interface Implementor {
    void operationImpl();
}

二、具体实现类(ConcreteImplementor)

java 复制代码
public class ConcreteImplementorA implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("ConcreteImplementorA operationImpl");
    }
}

public class ConcreteImplementorB implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("ConcreteImplementorB operationImpl");
    }
}

三、抽象类(Abstraction)

java 复制代码
public abstract class Abstraction {
    protected Implementor implementor;

    protected Abstraction(Implementor implementor) {
        this.implementor = implementor;
    }

    public abstract void operation();
}

四、扩展抽象类(RefinedAbstraction)

java 复制代码
public class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(Implementor implementor) {
        super(implementor);
    }

    @Override
    public void operation() {
        System.out.println("RefinedAbstraction operation");
        implementor.operationImpl();
    }
}

五、测试案例

java 复制代码
public class BridgePatternDemo {
    public static void main(String[] args) {
        Abstraction abstraction = new RefinedAbstraction(new ConcreteImplementorA());
        abstraction.operation();

        Abstraction anotherAbstraction = new RefinedAbstraction(new ConcreteImplementorB());
        anotherAbstraction.operation();
    }
}

桥接模式的应用场景

  • 当一个类存在两个独立变化的维度,且这两个维度都需要独立扩展时。
  • 当不希望使用继承来扩展一个类时,继承可能会导致系统类层次结构的爆炸式增长。
  • 当需要对客户端隐藏实现细节时。
相关推荐
阿狗童鞋3 小时前
设计模式实战指南
设计模式
电子科技圈9 小时前
基于车载SerDes和OpenGMSL协议的SoC设计与验证:行业高频问题解析
设计模式·车载系统·软件构建·设计规范
ClinicTech11 小时前
高速冷冻离心机的温控系统与安全保护逻辑解析
设计模式·架构·健康医疗·设计语言
GISMagic15 小时前
3.《设计模式》:软件设计与解耦能力提炼
设计模式·ai coding
染指111015 小时前
131.Agent-Agent设计模式-MAS多智能体系统(Multi-Agent-System)
人工智能·设计模式·langchain·agent·agents
ShyanZh1 天前
【Python3基础】13-Python 常用设计模式
开发语言·python·设计模式
YYYing.2 天前
【设计模式系列 (五) 】原型模式
开发语言·后端·设计模式·原型模式·c/c++
长按助力退休2 天前
设计模式实战,这 5 个最常用
设计模式
Carl_奕然2 天前
【智能体】Agent的四种设计模式之:Multi-Agent Collaboration
设计模式
Lost of 程序猿2 天前
建造者模式实战:告别“十参数构造函数“的数据导出任务
后端·设计模式·c#·asp.net