Builder Design Pattern….As the name suggests, builder pattern is a way to build objects. So it comes under creational design patterns. This is an efficient way to create immutable objects step by step which have a lot of optional parameters.
First, let us create the required object without using builder pattern
Requirements:
1) Final Object should be immutable( which implies that the class should not have any setter methods or any public attributes which can be set after object creation )
2) It should support a lot of optional parameters.
Lets say you are creating a worker registry for your organization for the purpose of printing Identity cards which tend to be immutable
The objects created from the above class will be immutable and optional parameters are allowed. Everything seems good ryt?? Well.. what if you want to introduce some more optional parameters in the future like address… then you have 3 options.
Option1 : You will have to add more constructors.
But in the end you will end up with large number of constructor methods which will make your code messy and unnecessarily large.
Option2 : You can create only one constructor which holds all the parameters something like below..
Worker( String fName, String lName, String gender, String emailAdrs, String maritalStatus, Date dob,.......)
This way while creating the object you have to pass null values to every optional parameter you don’t specify.
Option3 : You can add one constructor for mandatory parameters and use setter methods for optional parameters.
But then it looses immutability.
Hmm.. What to do now??? Here comes the builder pattern to our rescue..
In this pattern, you basically have 3 parts
- The Worker Class
- The builder for Worker object
- The client class or main method which uses the builder to create the worker object.
Now we can simply create the worker object like this..
public static void main(String[] args){
Worker worker = new Worker.WorkerBuilder(‘James’,‘Carl’,‘Male’)
.maritalStatus(‘married’)
.emailAdrs(‘abcd@domain.com’)
.build();
}
This way by chaining the methods , you can specify the optional parameters. We made the builder class an inner class so that this building process remains specific to this worker class.
Voila!!! We got our immutable object with optional parameters constructed step by step with readable code.
If you want to add an optional parameter in the future, you just have to add one more method to the Workerbuilder class.