The builder pattern is all about creating a complex object with the help of several simple objects. This is done in a step-by-step approach. This pattern falls under the category of creational design patterns. In simple terms, this pattern helps to produce different types and representations of an object with the same construction code.
Mostly used in situations where we need to create objects that have many different working parts and they all need to come together to create one single object.
“BioTechLanka” is a newly established plant-based research laboratory in Sri Lanka. This lab needs to store details of various plants.
Details to be stored —
The requirement — The system has to create different plant objects with the required details. Initially, we only need to provide the name of the plant. All the other details are optional.
After analyzing the above requirement, we can see that these objects have many optional and required fields.
First, let’s implement a solution without the help of Builder Design Pattern.
So this is the basic way of implementing the scenario.
What is the problem with this implementation?
Consider a situation where we need to add the category to the plant. We may have to implement it as follows,
- Had to pass several “Undefined” parameters.
- Parameters need to pass in the correct order.
- Not self-explanatory.
- Confusing for the developers.
- The overall process is complex.
How to solve this?
We can use the Builder Design pattern. There are 2 main ways to implement this Builder pattern.
Create a new Builder class for a plant and take all the required parameters to create a Plant object. In the above solution, just the name is enough for us to create a Plant Object. Then we need to create methods to set other parameters. Each of these methods returns “this” which in turn returns the builder back. This will give us the possibility to chain these methods together.
Let’s implement this.
We can chain these methods together because we are always returning the same object back.
Now we can set the relevant fields according to our requirement and get the object with the help of chaining. We don't need to specify “undefined” for all the optional parameters.
Similar to the 1st method, this method will look for the optional parameters. If there are not available, the JS engine will assign “undefined” value for them. We also have the option to assign a default value to these. Then the JS engine will assign these default values instead of “undefined”. This is one advantage of this method over the 1st one. Now we have successfully implemented the solution.
The following URL provides the complete source code for the above implementation.
Contribute to Damsak/Krish-LP-Training development by creating an account on GitHub.
I have used the following playlist by Mr.Krishntha Dinesh to gather the required information.
Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to…