Join us
Implementing Builder pattern is to build complex objects piece-by-piece providing more flexibility and readability to the code. In this article, we would learn when and how to implement Builder Pattern to build complex objects.
Constructor is also one of the way to create an object and it does have some cons to which Builder pattern covers up very well to create an object piece-by-piece and provides us with more flexibility creating an objects.
Generic approach is implemented in the process of constructing an object so that it can be used to create different representation of same object.
The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming.
When to use?
This pattern is to be implemented when:
Scenario
Let’s understand the pattern diving into a scenario where you went to create a profile on an E-commerce website.
Creating you profile for the first time will make you enter some of your details:
Now let’s say only firstname
and lastname
is mandatory.
Based on different combinations of entries made by user multiple constructor needs to be implemented to instantiate an object, making the code complex and multiple entries of constructor added into a class.
How to implement?
Considering the user creating his profile, that code that will be written using builder pattern would be:
Providing us with output
In Output 1
returns object with mandatory fields firstname
and lastname
while on the other hand with Output 2
we were able to add few more details to the same object, providing us with flexibility while creating an instance.
It provides with different set APIs to set properties of an object, in our case it’s StaysAt()
and ConnectOn()
which are not mandatory but can be used to set properties.
As the above created User
object does not have setter methods so the object cannot be updated, providing it an immutability.
Advantages
null
to optional parameters of constructor while creating an instance.Disadvantages
Happy Coding…!!!
More Readings:
Scheduling Jobs in Golang
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.