Builder Pattern

Danang Priabada
2 min readAug 31, 2023

--

Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

A Builder class builds the final object step by step. This builder is independent of other objects.

House Class

public class House {

//Primary
private String roof, wall, kitchen, bathroom, bedroom, livingRoom;

//Optional
private String basement, garage, diningRoom;

public House(HouseBuilder houseBuilder) {
this.roof = houseBuilder.roof;
this.wall = houseBuilder.wall;
this.kitchen = houseBuilder.kitchen;
this.bathroom = houseBuilder.bathroom;
this.bedroom = houseBuilder.bedroom;
this.garage = houseBuilder.garage;
this.livingRoom = houseBuilder.livingRoom;
this.diningRoom = houseBuilder.diningRoom;
this.basement = houseBuilder.basement;
}

public String getRoof() {
return roof;
}

public String getWall() {
return wall;
}

public String getKitchen() {
return kitchen;
}

public String getBathroom() {
return bathroom;
}

public String getBedroom() {
return bedroom;
}

public String getGarage() {
return garage;
}

public String getLivingRoom() {
return livingRoom;
}

public String getDiningRoom() {
return diningRoom;
}

public String getBasement() {
return basement;
}

public static class HouseBuilder {
//Primary
private String roof, wall, kitchen, bathroom, bedroom, livingRoom;

//Optional
private String basement, garage, diningRoom;

public HouseBuilder(String roof, String wall, String kitchen, String bathroom, String bedroom, String livingRoom) {
this.roof = roof;
this.wall = wall;
this.kitchen = kitchen;
this.bathroom = bathroom;
this.bedroom = bedroom;
this.livingRoom = livingRoom;
}

public HouseBuilder addBasement(String basement) {
this.basement = basement;
return this;
}

public HouseBuilder addGarage(String garage) {
this.garage = garage;
return this;
}

public HouseBuilder addDiningRoom(String diningRoom) {
this.diningRoom = diningRoom;
return this;
}

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

}

}

Main Class

import BuilderPatternTwo.House;

public class Main {
public static void main(String[] args) {

//Builder
House type1 = new House.HouseBuilder("1", "1", "1", "2", "2", "1").build();
House type2 = new House.HouseBuilder("1", "1", "1", "2", "2", "1").addGarage("1").build();
House type3 = new House.HouseBuilder("1", "1", "1", "2", "2", "1").addGarage("1").addBasement("1").build();

System.out.println("Type 1 = " + type1.getBasement());
System.out.println("Type 2 = " + type2.getBasement());
System.out.println("Type 3 = " + type3.getBasement());

}
}

Result

Type 1 = null
Type 2 = null
Type 3 = 1

--

--

Danang Priabada
Danang Priabada

Written by Danang Priabada

Red Hat and IBM Product Specialist | JPN : プリアバダ ダナン | CHN : 逹男 | linktr.ee/danangpriabada