JavaScript设计模式——抽象工厂模式

61 阅读1分钟

抽象工厂模式

抽象工厂模式提供一个创建一系列相关或相互依赖对象的家族,而无须指定它们具体的类。 抽象工厂模式主要包含4种角色:抽象工厂、具体工厂、抽象产品、具体产品。 抽象类提供接口的定义,具体类需要实现抽象接口。

typescript 代码

// 抽象产品
interface Button {
  paint(): void;
}

interface Label {
  paint(): void;
}

// 具体产品
class WinButton implements Button {
  paint() {
    console.log("WinButton is painted.");
  }
}

class WinLabel implements Label {
  paint() {
    console.log("WinLabel is painted.");
  }
}

class MacButton implements Button {
  paint() {
    console.log("MacButton is painted.");
  }
}

class MacLabel implements Label {
  paint() {
    console.log("MacLabel is painted.");
  }
}

// 抽象工厂
interface AbstractFactory {
  createButton(): Button;
  createLabel(): Label;
}

// 具体工厂
class WinFactory implements AbstractFactory {
  createLabel(): Label {
    return new WinLabel();
  }
  createButton(): Button {
    return new WinButton();
  }
}

class MacFactory implements AbstractFactory {
  createLabel(): Label {
    return new MacLabel();
  }
  createButton(): Button {
    return new MacButton();
  }
}

// 客户端
class App {
  private factory: AbstractFactory;

  constructor(factory: AbstractFactory) {
    this.factory = factory;
  }

  createUI() {
    const button: Button = this.factory.createButton();
    const label: Label = this.factory.createLabel();
    button.paint();
    label.paint();
  }
}

// 使用抽象工厂创建不同的 UI
const app1: App = new App(new WinFactory());
const app2: App = new App(new MacFactory());

app1.createUI();
app2.createUI();