设计模式-桥接模式

桥接模式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();
    }
}

桥接模式的应用场景

  • 当一个类存在两个独立变化的维度,且这两个维度都需要独立扩展时。
  • 当不希望使用继承来扩展一个类时,继承可能会导致系统类层次结构的爆炸式增长。
  • 当需要对客户端隐藏实现细节时。
相关推荐
范纹杉想快点毕业12 小时前
返璞归真还是拥抱现代?——嵌入式研发中的“裸机开发”与RTOS全景解析
c语言·数据库·mongodb·设计模式·nosql
代码笔耕1 天前
面向对象开发实践之消息中心设计(四)--- 面向变化的定力
java·设计模式·架构
程序员泠零澪回家种桔子1 天前
ReAct Agent 后端架构解析
后端·spring·设计模式·架构
阿闽ooo1 天前
深入浅出享元模式:从图形编辑器看对象复用的艺术
c++·设计模式·编辑器·享元模式
阿闽ooo1 天前
组合模式(Composite Pattern)深度解析:从原理到企业级实践
c++·笔记·设计模式·组合模式
山风wind1 天前
设计模式-策略模式详解
设计模式·策略模式
阿拉斯攀登1 天前
设计模式:实战概要
java·设计模式
阿拉斯攀登1 天前
设计模式:工厂模式概要
java·设计模式·抽象工厂模式
阿拉斯攀登1 天前
设计模式:构建者模式-示例二
设计模式·建造者模式
Coder_Boy_1 天前
Spring AI 设计模式综合应用与完整工程实现
人工智能·spring·设计模式