Hello!
Today I will share with you one of the most used design patterns, especially inside applications and frameworks, this pattern is called Factory and is widely used.
First of all, the patterns can be divided into three big groups: creation, behavior, and structural.
The factory pattern belongs to the creation concept, which is a way to have new instances of objects. With this approach, we can create reusable code that is more legible and has fewer problems with code duplicity since we will encapsulate the logic inside one class.
Factory Pattern 🤖
This pattern comes with the idea of having a class which is a boilerplate location to build your objects, holding every way to create the object and avoiding the propagation of different object creation throughout your code.
"You and your friend are working with the same entity, and then he is creating the entity without the first name in lowercase. In your case, this is mandatory. Then you are creating different instances in different files, and maybe you cannot know that because you didn't do the code review, so with that, you will have a bug later on."
This pattern helps to solve this kind of problem. The implementation can be something like:
class User {
constructor() {
this.id = null;
this.firstName = '';
}
setId(id) {
this.id = id;
return this;
}
getId() {
return this.id;
}
setFirstName(firstName) {
this.firstName = firstName;
return this;
}
getFirstName() {
return this.firstName;
}
}
class UserFactory {
constructor(id, firstName) {
this.id = id;
this.firstName = firstName;
}
create() {
return new User()
.setId(this.id)
.setFirstName(this.firstName.toLowerCase());
}
}
Afterward, you call this class in both places, applying the rules you need in only one place:
const user1 = new UserFactory(Date.now(), 'JhOn Cena').create();
console.log(\`ID - ${user1.getId()}, NAME - ${user1.getFirstName()}\`);
const user2 = new UserFactory(Date.now(), 'UNDERTAKER').create();
console.log(\`ID - ${user2.getId()}, NAME - ${user2.getFirstName()}\`);
With that, you avoid potential misuses of the code, and everybody knows where to see the logic of this particular object.
I suggest you dive into new materials about this. Refactoring Guru has a lot of examples 🔥
References:
Top comments (0)