Published on

Abstract Factory

Authors
  • avatar
    Name
    Khánh
    Twitter

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

  • Using the Factory Method Pattern to add many types within the same family is considered an Abstract Factory.
  • Using the Factory Method for many types that do not belong to the same family is not called an 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