Factory Method

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests

Source Code Listing

code.ts

/* eslint-disable @typescript-eslint/no-extraneous-class */

type Product = Record<string, unknown>;

class ConcreteProduct1 implements Product {
  [x: string]: unknown;
}

class ConcreteProduct2 implements Product {
  [x: string]: unknown;
}

abstract class Creator {
  operation(): void {
    const product = this.factoryMethod(1); // Example usage, could be parameterized
    if (product) {
      // Use the product
    }
  }

  abstract factoryMethod(id: number): Product | undefined;
}

class ConcreteCreator extends Creator {
  factoryMethod(id: number): Product | undefined {
    switch (id) {
      case 1: {
        return new ConcreteProduct1();
      }

      case 2: {
        return new ConcreteProduct2();
      }

      default: {
        return undefined;
      } // Handle unknown product types
    }
  }
}

const example = {
  run(): void {
    const creator = new ConcreteCreator();
    console.log(creator.factoryMethod(1));
    console.log(creator.factoryMethod(2));
    console.log(creator.factoryMethod(3)); // Now handles undefined
  },
};

example.run();