Today we will look into Builder pattern in java. Builder design pattern is a creational design pattern like Factory Pattern and Abstract Factory Pattern.
Builder pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. There are three major issues with Factory and Abstract Factory design patterns when the Object contains a lot of attributes.
We can solve the issues with large number of parameters by providing a constructor with required parameters and then different setter methods to set the optional parameters. The problem with this approach is that the Object state will be inconsistent until unless all the attributes are set explicitly. Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.
Let’s see how we can implement builder design pattern in java.
Computer
then builder class should be named as ComputerBuilder
.build()
method in the builder class that will return the Object needed by client program. For this we need to have a private constructor in the Class with Builder class as argument.Here is the sample builder pattern example code where we have a Computer class and ComputerBuilder class to build it.
package com.journaldev.design.builder;
public class Computer {
//required parameters
private String HDD;
private String RAM;
//optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public String getHDD() {
return HDD;
}
public String getRAM() {
return RAM;
}
public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}
public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}
private Computer(ComputerBuilder builder) {
this.HDD=builder.HDD;
this.RAM=builder.RAM;
this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
this.isBluetoothEnabled=builder.isBluetoothEnabled;
}
//Builder Class
public static class ComputerBuilder{
// required parameters
private String HDD;
private String RAM;
// optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public ComputerBuilder(String hdd, String ram){
this.HDD=hdd;
this.RAM=ram;
}
public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
this.isGraphicsCardEnabled = isGraphicsCardEnabled;
return this;
}
public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
this.isBluetoothEnabled = isBluetoothEnabled;
return this;
}
public Computer build(){
return new Computer(this);
}
}
}
Notice that Computer class has only getter methods and no public constructor. So the only way to get a Computer object is through the ComputerBuilder class. Here is a builder pattern example test program showing how to use Builder class to get the object.
package com.journaldev.design.test;
import com.journaldev.design.builder.Computer;
public class TestBuilderPattern {
public static void main(String[] args) {
//Using builder to get the object in a single line of code and
//without any inconsistent state or arguments management issues
Computer comp = new Computer.ComputerBuilder(
"500 GB", "2 GB").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
}
}
Recently I uploaded a YouTube video for Builder Design Pattern. I have also explained why I think the builder pattern defined on WikiPedia using Director classes is not a very good Object Oriented approach, and how we can achieve the same level of abstraction using different approach and with one class. Note that this is my point of view, I feel design patterns are to guide us, but ultimately we have to decide if it’s really beneficial to implement it in our project or not. I am a firm believer of KISS principle. https://www.youtube.com/watch?v=D5NK5qMM14g If you like the video, please do share it, like it and subscribe to my channel. If you think I am mistaken or you have any comments or feedback so that I can improve my videos in future, please let me know through comments here or on YouTube video page.
Some of the builder pattern example in Java classes are;
That’s all for builder design pattern in java.
You can download the example code from my GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Good article. Simple, lucid & very specific. Brings all the initialization complexity to inner class, which keeps you outer class clean, love this pattern. Is it like builder pattern cannot be implemented on those class whose attributes keep shifting from mandatory to optional and vice-versa, unless its designed to take every attributes thru the setter method of inner class.
- HIMANSU NAYAK
Good article. Why does below functions needs to return “this” when setting parameter? can you please give pointer on this?
- M
Hello Pankaj i have Question Why u have used only static nested class why not normal/regular inner class…i knw differences but in this example why we have used static nested clas only…plz reply…!
- Amritpal Singh
Hi Pankaj, There is still an issue with this approach. We are still expecting the client code to invoke the setters explicitly to ensure that the object state is consistent before the finally created object is returned upon invocation of build() method. We could have invoked the build method without even calling the setters and the boolean variables would have been initialized to false by default and still the object creation would have been successful with the consistent state. I think the another approach could be to provide a series of overloaded constructors with various combinations of optional parameters which invoke them in sequence until all the parameters are set and then the final object is created. In this case, we would not require to have even a build method. Please comment.
- Ashish
Can you please share/post UML design for the same as explain above Thanks Ashakant
- Ashakant
What is a need of getter and setter methods for outer class in above example if we are providing private constructor and no outer world can access the outer class?
- Rishi Naik
By this way, we can also create the object. Can you please explain the difference in using return this and the way below : public class TestBuilderPattern { public static void main(String[] args) { // Using builder to get the object in a single line of code and // without any inconsistent state or arguments management issues Computer.ComputerBuilder comp = new Computer.ComputerBuilder(“500 GB”, “2 GB”); comp.setBluetoothEnabled(true); comp.setGraphicsCardEnabled(true); comp.build(); System.out.println(comp); } public void setGraphicsCardEnabled(boolean isGraphicsCardEnabled) { this.isGraphicsCardEnabled = isGraphicsCardEnabled; // return this; } public void setBluetoothEnabled(boolean isBluetoothEnabled) { this.isBluetoothEnabled = isBluetoothEnabled; // return this; } }
- vijay
This blog was really nicely articulated and helpful. Thanks …
- Arijit Medya
Builder pattern described here is completely different from what other websites implementations. Here it shows with static inner class but others its not. Not sure which one is correct.
- Prabhakaran
I have one question that we are returning this in set() I know it is very important to return this in Builder pattern. But, Can you tell me what is the actual meaning when we return this and how it is actually executed. I have some confusions that how complier deal when we have used set() method of different fields for multiple times in same line of code while creating object and who will pick up this references of object before build().
- Kishan