Design Patterns in TypeScript: Factory Pattern

Imasha Weerakoon
2 min readMar 23, 2023

The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. In TypeScript, you can implement the Factory Pattern using an abstract class or an interface to define the Factory and concrete classes to implement it.

UML Diagram — Factory Pattern

Implementation

In this article, We will implement Factory Pattern using an interface.

Let’s assume a simple calculator doing calculations using two numbers. Included methods are adding, subtracting, multiplying, and dividing.

  1. Create a common interface for operation:
interface Operation {
execute(number1: number, number2: number): number;
}

2. Implement the operation interface for adding, subtracting, multiplying, and dividing:


class AddOperation implements Operation {
execute(number1: number, number2: number): number {
return number1 + number2;
}
}

class SubtractOperation implements Operation {
execute(number1: number, number2: number): number {
return number1 - number2;
}
}

class MultiplyOperation implements Operation {
execute(number1: number, number2: number): number {
return number1 * number2;
}
}

class DivideOperation implements Operation {
execute(number1: number, number2: number): number {
return number1 / number2;
}
}

3. Add a factory call to create an instance from operation implementations:

class OperationFactory {
getInstance(operation: string): Operation {
switch (operation) {
case '+':
return new AddOperation();
case '-':
return new SubtractOperation();
case '*':
return new MultiplyOperation();
case '/':
return new DivideOperation();
default:
throw new Error('Invalid operation');
}
}

4. Now you can execute any operation by simply parsing a string:

const operationFactory = new OperationFactory();
const operation = operationFactory.getInstance('+');
console.log(operation.execute(1, 2));

In this article, we discussed the Factory Pattern design pattern in TypeScript. There are many more. Let’s discuss others in the next articles.

You Don’t Need to ‘Reinvent the Wheel’

--

--