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

本文介绍了桥接器模式,一种结构型设计模式,通过分离抽象和实现部分以降低耦合,增加可扩展性和封装性。详细讲解了模式的组成要素、适用场景及一个实际的JavaScript实现示例。
摘要由CSDN通过智能技术生成

概念

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

具体内容

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

  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


  • 14
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值