The Significance of the Builder Design Pattern in Java
Pradeep H R
SDE @BT Group | Java, Spring Boot, Microservices, Apache Kafka, Quartz, Android, Flutter
(Get your basics strong with Simplified explanation along with an example)
Below we have Printer as Interface and 3 implementations of that interface.
public class Printer {
private String printType;
private String resolution;
private String speed;
private boolean color;
public Printer(String printType, String resolution, String speed, boolean color) {
this.printType = printType;
this.resolution = resolution;
this.speed = speed;
this.color = color;
}
@Override
public String toString() {
return "Printer{" +
"printType='" + printType + '\'' +
", resolution='" + resolution + '\'' +
", speed='" + speed + '\'' +
", color=" + color +
'}';
}
public static class PrinterBuilder {
private String printType;
private String resolution;
private String speed;
private boolean color;
public PrinterBuilder(String printType) {
this.printType = printType;
}
public PrinterBuilder setResolution(String resolution) {
this.resolution = resolution;
return this;
}
public PrinterBuilder setSpeed(String speed) {
this.speed = speed;
return this;
}
public PrinterBuilder setColor(boolean color) {
this.color = color;
return this;
}
public Printer build() {
return new Printer(printType, resolution, speed, color);
}
}
public static void main(String[] args) {
Printer laserPrinter = new Printer.PrinterBuilder("Laser")
.setResolution("1200 dpi")
.setSpeed("30 ppm")
.setColor(true)
.build();
System.out.println(laserPrinter);
}
}
The Builder Pattern in the Printer class offers:
Let's say you want to create an object but, the constructor takes 5 parameters, and you only want to pass 3 and skip the remaining 2 and let that 2 be taken default, Builder pattern kicks in there.