This content originally appeared on DEV Community and was authored by DEV Community
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.
Let's build our UML example and observe in practice using Typescript.
export interface IPerson {
name: string;
identifier(): void;
}
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";
}
}
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;
}
}
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.createProduct("N");
const legalPerson: IPerson = PersonFactory.createProduct("L");
}
}
That's all! We implement a Factory Design Pattern in Typescript and see about the UML representation.
Contacts
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca
This content originally appeared on DEV Community and was authored by DEV Community
DEV Community | Sciencx (2022-03-05T22:56:09+00:00) TypeScript Factory Design Pattern in practice (UML). Retrieved from https://www.scien.cx/2022/03/05/typescript-factory-design-pattern-in-practice-uml/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.