Builder Design Pattern Explained
The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation.
It is incredibly useful for creating objects that have many fields like required, optional, or other inner-making objects. Like I said It is more useful when you want to make an object that has many different working parts that should all come to an end object to return a parent object.
With an example, it will be very clear.
In our example, there are two classes name address and user. Basically, we want to create an object for the user. Passing the name value and checking console what returns in the console.
Here we can see the user name is Siam and other fields are empty. But if we want to pass the value of the phone and name and don't want to send others what we can do.
We can pass the given way below and also see the result in the console
This is not the right way to pass the value or set the value because if there are more than 20 or 50 parameters to pass it is quite difficult to track the value which is sent and which is not. To solve this issue we use builder design pattern
Here we are using UserBuilder to solve this issue
And it returns an object with the name and phone
In modern javascript, we actually don't need the build class anymore. Now we actually going to do work on the user class. As we know from the above name is required. Besides that, there are many parameters that are optional and the easy way to pass them in a JSON object or javascript object in the very end
If we want to only send the name then we should assign those parameters with a default value. In the example, we are assigning the default value with an empty javascript object