Design pattern: Factory Method (TypeScript examples)
Published in
4 min readJul 30, 2023
Factory method is a creational design pattern that solves the problem of creating product objects without specifying their concrete classes.
Here’s an example of implementation in TypeScript:
// Product: Shape interface
interface Shape {
draw(): void;
}
// Concrete Products
class Circle implements Shape {
draw() {
console.log("Drawing a circle.");
}
}
class Square implements Shape {
draw() {
console.log("Drawing a square.");
}
}
//Next, we'll create the Creator (Factory) interface and the Concrete Creators:
// Creator (Factory) interface
interface ShapeFactory {
createShape(): Shape;
}
// Concrete Creators
class CircleFactory implements ShapeFactory {
createShape() {
return new Circle();
}
}
class SquareFactory implements ShapeFactory {
createShape() {
return new Square();
}
}
// Now, let's see how the client code (consumer) can use the Factory Method to create shapes without knowing their specific types:
function drawShape(factory: ShapeFactory) {
const shape = factory.createShape();
shape.draw();
}
// Client Code
drawShape(new CircleFactory());
drawShape(new SquareFactory());
Output:
Drawing a circle.
Drawing a square.
In this example, we have implemented the Factory Method design pattern to create different shapes in…