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

概念

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

具体内容

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

  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


原文地址:https://blog.csdn.net/weixin_44863521/article/details/135538258

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_56058.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注