设计模式-桥接模式

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

桥接模式的应用场景

  • 当一个类存在两个独立变化的维度,且这两个维度都需要独立扩展时。
  • 当不希望使用继承来扩展一个类时,继承可能会导致系统类层次结构的爆炸式增长。
  • 当需要对客户端隐藏实现细节时。
相关推荐
AI大法师2 小时前
从 Firefox Kit 看懂品牌升级的正确顺序
大数据·人工智能·设计模式·firefox
天若有情6732 小时前
原创C++设计模式:功能归一化——无继承、轻量版AOP,比传统OOP更优雅
开发语言·c++·设计模式·oop
绿豆人20 小时前
Go设计模式学习
学习·设计模式·golang
逮到647了1 天前
23种设计模式简述
设计模式
爱吃烤鸡翅的酸菜鱼1 天前
【Java】封装位运算通用工具类——用一个整数字段替代几十个布尔列,极致节省存储空间
java·开发语言·设计模式·工具类·位运算·合成复用原则
geovindu1 天前
go: Model,Interface,DAL ,Factory,BLL using mysql
开发语言·mysql·设计模式·golang·软件构建
guojb8241 天前
当 Vue 3 遇上桥接模式:手把手教你优雅剥离虚拟滚动的业务大泥球
vue.js·设计模式
我登哥MVP1 天前
【Spring6笔记】 - 15 - Spring中的八大设计模式
java·spring boot·笔记·spring·设计模式·intellij-idea
无籽西瓜a1 天前
【西瓜带你学设计模式 | 第十六期 - 迭代器模式】迭代器模式 —— 统一遍历实现、优缺点与适用场景
java·后端·设计模式·迭代器模式·软件工程
程序员小寒1 天前
JavaScript设计模式(十):模板方法模式实现与应用
前端·javascript·设计模式·模板方法模式