Continuing from our Design Patterns series, we will talk about the Builder Pattern – another creational pattern in this blog.
The Builder Pattern
Like other patterns mentioned in my previous blogs, the builder pattern is also used to create objects. The builder pattern helps build a complex object step by step without breaking the actual object. This helps in building different objects with varying properties with the same construction code.
Use Case
The main use of the builder pattern is that it reduces the need for a very big constructor with large numbers of parameters.
Let's look at an example. Here, we have a Person class that accepts constructor parameter as name, education, age, and height.
When we want to construct a person object without education, we have to pass null in place of education. A simple demo is shown below:
The example shown above might look simple enough, but having many parameters in the constructor will make the code look hard to read.
Design Diagram
What if there were 10 , 15 or even 20+ parameters while constructing an object? You would get confused really fast about what parameter you are passing. So to solve this issue, we use a builder pattern.
Implementation
Let's go through implementing such a design pattern with an example.
First, we need to determine all the construction steps required for building an object. A simple interface for the builder will have all this steps defined. In my example, I have created a ICharacterBuilder class that has all steps for generating a character. Then,CharacterBuilder will implement from the ICharacterBuilder.
All methods used as steps to build a final product will return a builder reference, which is shown below by returning this in all methods. We need to add one method that will create a product based on steps taken and return a final product. I am using the Build method to create a Character object and return it.
We can also add director if we want, which will encapsulate creation of final product using builder object. The client will create both a builder and a director object and pass the builder to the director. The director will then take the required steps and produce a final product. In my implementation, I have not used a director. I am using the builder to directly create an object.
Code and Execution
That's all for today, hope you learned something new from this. I will be writing about more patterns soon.