Skip to content

适配器设计模式 / Adapter

适配器设计模式允许把一个类的接口转换成另一个类的接口,以使原本接口不兼容的类可以一起工作。

Code

javascript
class Printer {
  print(text) {}
}

class LegacyPrinter {
  legacyPrint(text) {
    console.log(`LegacyPrint: ${text}`);
  }
}

class PrinterAdapter extends Printer {
  constructor() {
    super();
    this.legacyPrinter = new LegacyPrinter();
  }
  print(text) {
    this.legacyPrinter.legacyPrint(text);
  }
}

const printer = new PrinterAdapter();
printer.print('Hello'); // -> LegacyPrint: Hello