I have discussed Singleton Pattern, Observer Pattern, Factory Pattern, Decorator Pattern, and Command Pattern in my previous posts. In this one I will be talking about the Builder Design Pattern.
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
null
for 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.
Java Implementation
- Create a
User
class, make the constructor private, so that objects of this class cannot be built directly. - Create a
UserBuilder
class. 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.
Reference
https://howtodoinjava.com/design-patterns/creational/builder-pattern-in-java/