Zachary W. Huang

Home Projects Blog Guides Resume

Abstract Factory

Idea: Define an abstract “Factory” class which generates products. We can alter every product by simply changing which factory is used.

Example: Using an abstract factory to generate differently-themed GUI widgets - switch styles by simply changing the concrete factory used.

interface ProductOne {}
interface ProductTwo {}

abstract class Factory {
  abstract makeProductOne(): ProductOne;
  abstract makeProductTwo(): ProductTwo;
}

class FactoryA extends Factory {
  makeProductOne() {
    return { contents: 1, style: "A" }
  }
  makeProductTwo() {
    return { contents: 2, style: "A" }
  }
}

class FactoryB extends Factory {
  makeProductOne() {
    return { contents: 1, style: "B" }
  }
  makeProductTwo() {
    return { contents: 2, style: "B" }
  }
}

function main(factory: Factory) {
  const factory = new FactoryA();
  const thing1 = factory.makeProductOne();
  const thing2 = factory.makeProductTwo();
  console.log(thing1.style, thing2.style); // "A  A"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024