Let’s say we want to create an Employee class that has the below mandatory and optional attributes.
The Employee class and its constructor looks like below
The main problem with the above constructor is that we have to manually pass null values for the optional attributes that we don’t want to use.
It looks simple in our class, but consider a complex class with more mandatory and optional attributes. And we also don’t know which one is mandatory and which one is optional.
Another way to create an Employee class is to have multiple constructors for the required combination of the attributes which is even complex.
Here comes the lifesaver, Builder Design Pattern.
Builder pattern builds a complex object using simple objects and using a step by step approach
In Builder Pattern, the actual class relies on another class called Builder Class for object creation.
Using Builder Pattern, an object can be created using multiple steps, An Initial Step, 0 or more Intermediate Steps, and Terminal Step.
Now, we added a nested class inside the Employee class called EmployeeBuilder. The EmployeeBuilder class will be responsible for the construction of the Employee object.
All the mandatory attributes can be set via the EmployeeBuilder constructor.
All the optional attributes can be set via the public setter methods setSecondaryMobileNumber and setSecondaryEmail
Once all the attributes are set, the object can be created by calling the build method of the EmployeeBuilder class. The build method creates and returns an Employee object.
The constructor of the Employee class is made private so that it can be accessed only from the EmployeeBuilder class.
Now, the object can be created using the EmployeeBuilder class as given below
The entire source code can be found in the below gist
Thank you 🤘