Sunday 11 October 2020

Create Builder Design Pattern in Java

Builder Design Pattern in Java

The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.


The builder pattern, as name implies, is an alternative way to construct complex objects. This should be used only when you want to build different immutable objects using same object building process.



package com.vehicle;


public class Car {

private final String carCompany;

private final String name;

private final String model;

private final String colour;

private final String engine;

private Car(Builder builder) {

this.carCompany=builder.carCompany;

this.name=builder.name;

this.model=builder.model;

this.colour=builder.colour;

this.engine=builder.engine;

}

//All getter, and NO setter to provde immutability in Car

public String getName() {

return this.name;

}

public String getModel() {

return this.model;

}

public String getColour() {

return this.colour;

}

public String getEngine() {

return this.engine;

}

public static class Builder{

   

private final String carCompany;

private String name;

private String model;

private String colour;

private String engine;

public Builder(String carCompany){

this.carCompany = carCompany;

}

public Builder setName(String name) {

this.name=name;

return this;

}

public Builder setModel(String model) {

this.model=model;

return this;

}

public Builder setColour(String colour) {

this.colour=colour;

return this;

}

public Builder setEngine(String engine) {

this.engine=engine;

return this;

}

public Car build() {

return new Car(this);

}

}

@Override

public String toString() {

return "Builder [carCompany=" + carCompany + ", name=" + name + ", model=" + model + ", colour=" + colour+ ", engine=" + engine + "]";

}

}


------------------------------------------------------------------------------------------------------------------------


package com.vehicle;


public class Main {


public static void main(String[] args) {


Car car1 = new Car.Builder("Maruti").setName("Alto").setEngine("900CC").setModel("k10Vxi").build();

Car car2 = new Car.Builder("Ford").setName("Escort").setEngine("1600CC").setModel("MK2").build();

System.out.println(car1);

System.out.println(car2);

}


}





No comments:

Post a Comment