· Last updated on

Abstract Factory

typescriptdesign-pattern

Problems

During software development, there may be times when we need to create a family of objects of a specific type, such as a family of wooden furniture, a family of iron furniture, a family of aluminum furniture, etc.

Abstract Factory

Examples


abstract class Chair {
  hasLegs: boolean;
  sitOn: () => void;
}

class VictorianChair implements Chair {
  hasLegs: boolean;
  sitOn: () => void;
}

class ModernChair implements Chair {
  hasLegs: boolean;
  sitOn: () => void;
}

abstract class Table {
  hasLegs: boolean;
  sitOn: () => void;
}

class VictorianTable implements Table {
  hasLegs: boolean;
  sitOn: () => void;
}

class ModernTable implements Table {
  hasLegs: boolean;
  sitOn: () => void;
}

abstract class FurnitureFactory {
  createChair: () => Chair;
  createTable: () => Table;
}

// Create a family of Victorian Furniture
class VictorianFurnitureFactory implements FurnitureFactory {
  createChair() {
    return new VictorianChair();
  }
  createTable() {
    return new VictorianTable();
  }
}

// Create a family of Modern Furniture
class ModernFurnitureFactory implements FurnitureFactory {
  createChair() {
    return new ModernChair();
  }
  createTable() {
    return new ModernTable();
  }
}

References