Design Patterns - Static Factory Method Pattern in TypeScript
Before you look at the Static Factory Method pattern example in TypeScript, you can see my post about what is the Static Factory Method pattern.
Example of the static factory method in TypeScript
class User {
private firstName: string;
private lastName: string;
private email: string;
get getFirstName(): string {
return this.firstName;
}
get getLastName(): string {
return this.lastName;
}
get getEmail(): string {
return this.email;
}
private constructor(firstName: string, lastName: string, email: string) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
static create(firstName: string, lastName: string, email: string): User {
return new User(firstName, lastName, email);
}
}
About this code snippet:
- The constructor is private.
- To create new instances of the user class, just use the static factory method with:
User.create("John", "Doe", "john@doe.com")
.
Categories
Automation scripting Development tools Front end web development Infrastructure Kubernetes Programming guide Security Software architectureTags
Recent Posts
Restart Kubernetes pods following a schedule using Helm
Restart Kubernetes pods following a schedule using Kubectl
Create an Azure Key Vault with RBAC role assignments using Terraform
Get the download url of the latest GitHub release using Bash
Get the download url of the latest GitHub release using PowerShell