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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters