Builder Design Pattern Tutorial with Practical Examples in Java
In builder design pattern we removed the logic related to object constructor from client code & abstract it in separate class.
This pattern was introduced to solve some of the problems with factory design pattern when the object contains a lot of attributes . major issues with factory design pattern is when object contains a lot of attributes.
Some of the parameters might be optional but in factory pattern. we are forced to send all the parameters and optional parameters need to send as Null.
Structure of Builder Pattern
It has 4 main parts:
- Product → Final object (
Car,User) - Builder → Builds the object step-by-step
- Fluent Methods → Chainable setters
- Build Method → Returns final object
Example : Builder design pattern Implementation
1.Car.java
public class Car {
// Required parameters
private String engine;
private int wheels;
// Optional parameters
private boolean sunroof;
private boolean airConditioner;
private String color;
// Private constructor
private Car(Builder builder) {
this.engine = builder.engine;
this.wheels = builder.wheels;
this.sunroof = builder.sunroof;
this.airConditioner = builder.airConditioner;
this.color = builder.color;
}
// Static inner Builder class
public static class Builder {
// Required parameters
private String engine;
private int wheels;
// Optional parameters - initialized with default values
private boolean sunroof = false;
private boolean airConditioner = false;
private String color = "White";
// Constructor with required parameters
public Builder(String engine, int wheels) {
this.engine = engine;
this.wheels = wheels;
}
// Setter methods for optional parameters
public Builder setSunroof(boolean sunroof) {
this.sunroof = sunroof;
return this;
}
public Builder setAirConditioner(boolean airConditioner) {
this.airConditioner = airConditioner;
return this;
}
public Builder setColor(String color) {
this.color = color;
return this;
}
// Build method to create object
public Car build() {
return new Car(this);
}
}
@Override
public String toString() {
return "Car [engine=" + engine +
", wheels=" + wheels +
", sunroof=" + sunroof +
", AC=" + airConditioner +
", color=" + color + "]";
}
}
2. Main.java
public class TestBuilderDesignPattern{
public static void main(String[] args) {
Car car = new Car.Builder("V8 Engine", 4)
.setSunroof(true)
.setAirConditioner(true)
.setColor("Black")
.build();
System.out.println(car);
}
}