设计模式-桥模式

22 阅读1分钟

定义

桥模式,是一种结构型模式,用于将抽象部分与其实现部分分离,使他们可以独立变化。

这种模式通过提供一个桥接结构,而不是通过继承来组织代码。

UML 类图

typescript 实现

1. 实现层接口

interface Implementor {
  method1(): void;
  method2(): void;
  method3(): void;
}

2. 创建具体实现类

class ConcreteImplementorA implements Implementor {
  method1() {
    console.log("ConcreteImplementorA method1");
  }
  method2() {
    console.log("ConcreteImplementorA method2");
  }
  method3() {
    console.log("ConcreteImplementorA method3");
  }
}

class ConcreteImplementorB implements Implementor {
  method1() {
    console.log("ConcreteImplementorB method1");
  }
  method2() {
    console.log("ConcreteImplementorB method2");
  }
  method3() {
    console.log("ConcreteImplementorB method3");
  }
}

3. 创建抽象层类

class Abstraction {
  protected implementor: Implementor;
  constructor(implementor: Implementor) {
    this.implementor = implementor;
  }
  operation() {
    this.implementor.method1();
    this.implementor.method2();
    this.implementor.method3();
  }
}

4. 创建扩展抽象层类

class RefinedAbstraction extends Abstraction {
  simpleOperation() {
    this.implementor.method1();
  }
}

5. 示例

const implementorA = new ConcreteImplementorA();
const abstractionA = new RefinedAbstraction(implementorA);
abstractionA.simpleOperation();

const implementorB = new ConcreteImplementorB();
const abstractionB = new RefeindAbstraction(implementorB);
abstractionB.simpleOperation();

通用实现

// 公共代码
export class Abstraction<T> {
  protected implementor: T;
  constructor(implementor: T) {
    this.implementor = implementor;
  }
}

// 私有代码,实现层接口
interface Codec {
  encode(): void;
  decode(): void;
}

// 私有代码,实现层具体类
class H264 implements Codec {
  encode() {
    console.log("encode h264");
  }
  decode() {
    console.log("decode h264");
  }
}

class VP8 implements Codec {
  encode() {
    console.log("encode vp8");
  }
  decode() {
    console.log("decode vp8");
  }
}

// 私有代码,抽象层
class AVBuffer extends Abstraction<Codec> {
  constructor(codec: Codec) {
    super(codec);
  }
  play() {
    this.implementor.decode();
    console.log("playing decode content");
  }
  store() {
    this.implementor.encode();
    console.log("storing encode content");
  }
}

// 私有代码,示例
const avBuffer = new AVBuffer(new H264());
avBuffer.play();