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

概念

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

具体内容

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

  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
相关推荐
afumu16 分钟前
免费 API 满地都是,为什么还有人做「让网页 AI 干活」这种东西
javascript·chrome·浏览器
云起SAAS22 分钟前
本地生活同城多商户商城系统源码源码 合伙人分红加区域代理加排队返现
前端·javascript·后端
wy_hhxx1 小时前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
鹿鹿鹿鹿isNotDefined1 小时前
布局更新后,canvas 重新绘制,出现了只持续一帧的闪烁?!
前端·javascript·vue.js
技术分享官1 小时前
Geejing WebBuilder 新手指导:用 Wb.Button 按钮组件跑通企业级快速开发平台的前后端闭环
前端·javascript·低代码
AAA修煤气灶刘哥1 小时前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
程序员大阳5 小时前
副队长ES6+教程(5)--模板字符串
javascript·vue.js·es6·模板字符串
安若浮生5 小时前
从零写一个 HarmonyOS NEXT 影视聚合播放器,我踩过的 14 个坑
javascript
程序员大阳5 小时前
副队长ES6+教程(4)--拓展运算符
javascript·vue.js·es6·收集·拓展运算符·展开
Mh6 小时前
AI 的模型能力越来越强,为什么我的编码能力越来越弱?
前端·javascript·后端