一天一个设计模式---桥接模式

概念

桥接器模式是一种结构型设计模式,旨在将抽象部分与实现部分分离,使它们可以独立变化而不相互影响。桥接器模式通过创建一个桥接接口,连接抽象和实现,从而使两者可以独立演化。

具体内容

桥接器模式通常包括以下几个要素:

  1. 抽象类(Abstraction): 定义抽象部分的接口,维护一个指向实现部分的引用。
  2. 扩充抽象类(Refined Abstraction): 对抽象类的扩展,可以引入更多的抽象行为。
  3. 实现接口(Implementor): 定义实现部分的接口,该接口不一定要与抽象接口完全一致,但必须能够被抽象接口调用。
  4. 具体实现类(Concrete Implementor): 实现实现接口,提供具体的实现。

类结构图

适用场景

  • 分离抽象和实现: 允许抽象部分和实现部分独立变化,降低它们之间的耦合性。
  • 可扩展性: 可以方便地添加新的抽象类和实现类,不影响现有的类结构。
  • 隐藏细节: 客户端仅与抽象接口交互,不需要关心实现的细节,提高了系统的封装性。

实现

JS 复制代码
// 实现接口
class Implementor {
  operationImpl() {
    console.log("Implementor operation");
  }
}

// 具体实现类A
class ConcreteImplementorA extends Implementor {
  operationImpl() {
    console.log("Concrete Implementor A operation");
  }
}

// 具体实现类B
class ConcreteImplementorB extends Implementor {
  operationImpl() {
    console.log("Concrete Implementor B operation");
  }
}

// 抽象类
class Abstraction {
  constructor(implementor) {
    this.implementor = implementor;
  }

  operation() {
    console.log("Abstraction operation ->");
    this.implementor.operationImpl();
  }
}

// 扩充抽象类
class RefinedAbstraction extends Abstraction {
  constructor(implementor) {
    super(implementor);
  }

  operation() {
    console.log("Refined Abstraction operation ->");
    this.implementor.operationImpl();
  }
}

// 客户端代码
const implementorA = new ConcreteImplementorA();
const implementorB = new ConcreteImplementorB();

const abstractionA = new RefinedAbstraction(implementorA);
const abstractionB = new RefinedAbstraction(implementorB);

abstractionA.operation(); // 输出:Refined Abstraction operation -> Concrete Implementor A operation
abstractionB.operation(); // 输出:Refined Abstraction operation -> Concrete Implementor B operation
相关推荐
kkkAloha11 分钟前
JS笔记汇总
开发语言·javascript·笔记
刀法如飞9 小时前
开箱即用的 DDD(领域驱动设计)工程脚手架,基于 Spring Boot 4.0.1 和 Java 21
java·spring boot·mysql·spring·设计模式·intellij-idea
哈__10 小时前
React Native 鸿蒙跨平台开发:PixelRatio 像素适配
javascript·react native·react.js
用户63879947730511 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
DarkLONGLOVE11 小时前
Vue组件使用三步走:创建、注册、使用(Vue2/Vue3双版本详解)
前端·javascript·vue.js
DarkLONGLOVE11 小时前
手把手教你玩转Vue组件:创建、注册、使用三步曲!
前端·javascript·vue.js
冴羽12 小时前
2026 年前端必须掌握的 4 个 CSS 新特性!
前端·javascript·css
狗头大军之江苏分军12 小时前
告别旧生态:Ant Design 6 不再支持 IE 与现代前端趋势解读
前端·javascript·后端
Highcharts.js13 小时前
Highcharts Grid 表格/网格安装 |官方安装文档说明
开发语言·javascript·表格组件·highcharts·官方文档·安装说明·网格组件
GISer_Jing13 小时前
AI Agent 人类参与HITL与知识检索RAG
人工智能·设计模式·aigc