DEV Community

Cover image for TypeScript Factory Design Pattern in practice (UML)
Luiz Calaça
Luiz Calaça

Posted on • Updated on

TypeScript Factory Design Pattern in practice (UML)

Hello, Devs!

Design Patterns help us to build a better softwares and like this we can architect the solutions for the knew problems. So, there are a Gang of Four that wrote the book Design Patterns and show us design for problems in creational, structural or behavioral object oriented programming context.

Let's see how to use the Factory Pattern in Typescript, but what is it?

Factory Pattern is one of the Creational Design Pattern. We must use when we need to create an object without exposing the creation logic to the client and refer to newly created objects using a common interface. So we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class.

We can see in UML (Unified Modeling Language) the representation of this pattern.

Factory Design Pattern UML

Let's build our UML example and observe in practice using Typescript.

Factory Design Pattern UML

export interface IPerson {
    name: string;
    identifier(): void;
}
Enter fullscreen mode Exit fullscreen mode

And then implements:

export class NaturalPerson implements IPerson {
    name: string

    constructor() { this.name = '' }

    identifier() {
        return "Identifier of NaturalPerson";
    }
}

export class LegalPerson implements IPerson {
    name: string

    constructor() { this.name = '' }

    identifier() {
        return "Identifier of LegalPerson";
    }
}
Enter fullscreen mode Exit fullscreen mode

And then our Factory with a static method:

export class PersonFactory {
    public static createPerson(type: string) : IPerson {
        if (type === "N") {
            return new NaturalPerson();
        } else if (type === "L") {
            return new LegalPerson();
        }

        return null as unknown as IPerson;
    }
}


Enter fullscreen mode Exit fullscreen mode

And now our usage way. Here we suppose the we have a folder person with IPerson and PersonFactory and the class Main is outside.

import { IPerson, PersonFactory } from "./person";

export class Main {
    main(){
      const naturalPerson: IPerson = PersonFactory.createPerson("N");
      const legalPerson: IPerson = PersonFactory.createPerson("L");
    }
}

Enter fullscreen mode Exit fullscreen mode

That's all! We implement a Factory Design Pattern in Typescript and see about the UML representation.

https://www.buymeacoffee.com/calaca

Contacts
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca

Oldest comments (0)