Builder design pattern in java?

The Builder design pattern is used to creates a complex object by using a step by step approach. It is very helpful when you have a large number of attributes in class and you want to create an object. The Builder class creates the final object step by step and it is independent of other objects.

Why we need builder design pattern?

Build design pattern is used to create construct complex object.

It is a way to build different immutable objects using same object building process.

Implementation of builder pattern java

We have to create a static nested class(Inner static class) that is known Builder class. The builder class copies all the properties from the outer class to the Builder class.

The Builder class will contain a public constructor only with required attributes.

The Builder class will contain some setters for optional attributes and it will return the same Builder object.

The Builder class will have a build() method that will return the Object needed by the client program. For this we need to have a private constructor in the Class with Builder class as argument.

public class Car {
private final String insurance;
private final Boolean etc;
private final String roadAssistance;
private final String dropOffLocation;

public Car(Builder builder){
this.insurance= builder.insurance;
this.etc= builder.etc;
this.roadAssistance= builder.roadAssistance;
this.dropOffLocation= builder.dropOffLocation;
}

static class Builder{
private String insurance;
private Boolean etc;
private String roadAssistance;
private String dropOffLocation;

public Car build() {
return new Car(this);
}

public Builder(String insurance){
this.insurance =insurance;
}
public Builder etc(Boolean etc){
this.etc = etc;
return this;
}
public Builder roadAssistance(String roadAssistance){
this.roadAssistance = roadAssistance;
return this;
}
public Builder dropOffLocation(String dropOffLocation){
this.dropOffLocation = dropOffLocation;
return this;
}

@Override
public String toString() {
return "Builder{" +
"insurance='" + insurance + '\'' +
", etc=" + etc +
", roadAssistance='" + roadAssistance + '\'' +
", dropOffLocation='" + dropOffLocation + '\'' +
'}';
}


}
}