Design pattern: Factory Method (TypeScript examples)

Kristiyan Velkov
Front-end World

--

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…

--

--

Kristiyan Velkov
Front-end World

Front-end Advocate || Meta Certified React JS Developer || Tech lead || Speaker || Blogger React js, Next.js, Angular, Vue.js, Docker, People management