A small example of the Builder Pattern in Java. We are going to build cars with different colors, brands and models 🙂
Car.java
public class Car {
private String brand;
private String color;
private String model;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
CarBuilder.java
public class CarBuilder {
private Car car;
private CarBuilder() {
car = new Car();
}
public static CarBuilder aCar() {
return new CarBuilder();
}
public CarBuilder withBrand(String brand) {
car.setBrand(brand);
return this;
}
public CarBuilder withColor(String color) {
car.setColor(color);
return this;
}
public CarBuilder withModel(String model) {
car.setModel(model);
return this;
}
public Car build() {
return car;
}
}
With these two classes above we can now build some cars:
Main.java
public class Main {
public static void main(String[] args) {
Car myFirstCar = CarBuilder.aCar().withBrand("Volvo")
.withColor("Blue")
.withModel("XC90")
.build();
Car mySecondCar = CarBuilder.aCar().withBrand("Skoda")
.withColor("Grey")
.withModel("130L")
.build();
System.out.println("My first car was a " + myFristCar.getBrand());
System.out.println("My second car was a " + mySecondCar.getBrand());
}
}
Should print:
My first car was a Volvo My Second car was a Skoda
Tested on Ubuntu 20.04.4 LTS and Java 21