What is the Builder Design Pattern?
Builder pattern helps us in creating an immutable class with a large set of state attributes. One of the popular methods of implementing a class when you want to have an immutable object is to define a constructor with all the parameters, and no setter methods.
For example: Defining a user class with Firstname, Lastname, age, email.
What happens if some of these fields are optional. You have 2 options:
- Expect the clients to pass
nullfor these fields.
If you add a new field to this class, all these clients will have to be edited.
- Have as many constructors as there are combinations of these fields.
You will have a bloated class if the number of fields are on the higher side.
Builder pattern helps address this issue without giving up on the immutability of the class.
- Create a
Userclass, make the constructor private, so that objects of this class cannot be built directly.
- Create a
UserBuilderclass. This will be the builder class for our user class.
Using this pattern (Main)
As you see above, you have the flexibility of adding none or more optional attributes.
You can find the complete code on Github.
Advantages of Builder Design Pattern
- It helps in providing code readability and design flexibility.
- There is no need to pass in null for optional parameters to the constructor.
- Object is always instantiated with a complete state.
- Building an immutable object does not require complex logic at the time of building.
Disadvantages of Builder Design Pattern
- The number of lines of code more than doubles due to the builder class.
Builder Pattern in Java Library
The widely used StringBuilder and StringBuffer are both good examples of Builder pattern.