当前位置: 首页 > news >正文

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

概念

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

具体内容

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

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

类结构图

在这里插入图片描述

适用场景

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

实现

// 实现接口
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
http://www.lryc.cn/news/278590.html

相关文章:

  • OpenHarmony4.0Release系统应用常见问题FAQ
  • Skywalking UI页面中操作的各种实用功能汇总
  • springboot摄影跟拍预定管理系统源码和论文
  • 【python】python新年烟花代码【附源码】
  • 书生·浦语大模型实战营-学习笔记1
  • ELF解析03 - 加载段
  • Mysql——索引相关的数据结构
  • 无代码DIY图像检索
  • Elasticsearch--Master选举
  • 微服务实战系列之Filter
  • 使用GPT大模型调用工具链
  • C语言实现bmp图像底层数据写入与创建
  • 基于BP神经网络的定位算法,基于BP神经网络定位预测
  • Java Http各个请求类型详细介绍
  • python函数装饰器参数统计调用时间和次数
  • 机器学习之集成学习AdaBoost
  • 行云部署成长之路 -- 慢 SQL 优化之旅 | 京东云技术团队
  • Windows权限提升
  • win系统搭建Minecraft世界服务器,MC开服教程,小白开服教程
  • word2vec中的CBOW和Skip-gram
  • 在ios上z-index不起作用问题的总结
  • 力扣labuladong一刷day59天动态规划
  • pyenv环境找不到sqlite:No module named _sqlite3
  • Histone H3K4me2 Antibody, SNAP-Certified™ for CUTRUN
  • 我用 Laf 开发了一个非常好用的密码管理工具
  • windows项目部署
  • http首部
  • 2024.1.8 Day04_SparkCore_homeWork
  • 09.简单工厂模式与工厂方法模式
  • DHCP,怎么在Linux和Windows中获得ip