设计模式-适配器模式

24 阅读1分钟

定义

适配器模式,是一种结构型设计模式,它允许将不兼容的接口之间进行交互。

适配器模式通过将一个类的接口转换成客户端期望的另一个接口来实现,使得原本由于接口不兼容而不能一起工作的那些类一起工作。

UML 类图

typescript 实现

1. 目标接口

interface Target {
  request(): string;
}

2. 被适配的类

class Adaptee {
  public adapteeRequest(): string {
    return "Adaptee Request";
  }
}

3. 适配器类

class Adapter implements Target {
  private adaptee: Adaptee;
  constructor(adaptee: Adaptee) {
    this.adaptee = adaptee;
  }
  request() {
    const result = this.adaptee.adapteeRequest();
    return `Adapter: (TRANSLATED) ${result}`
  }
}

4. 使用示例

function clientCode(target: Target) {
  console.log(target.request());
}

console.log("Client: I can work just fine with the Target objects:");
const target = new Adapter(new Adaptee());
clietCode(target);

通用实现

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

// 私有代码,目标接口
interface Food {
  eat(): string;
}

// 私有代码,被适配类
class Rice {
  public cook() {
    return `Cook Rice`;
  }
}

// 私有代码,适配器类
class RiceAdapterForFood extends Adapter<Rice> implements Food {
  constructor(adaptee: Rice) {
    super(adaptee);
  }
  eat() {
    const result = this.adaptee.cook();
    return `Adapter: ${result}`;
  }
}

// 私有代码,示例
const food = new RiceAdapterForFood(new Rice());