Design Pattern: Builder Pattern in Java

Builder pattern is used to hide the complexity of building complex objects from the client and also this pattern is responsible for building objects step-by-step.

Check complete details and explanations about the Builder Pattern in the article: Builder Design Pattern

This article demonstrates Builder pattern implementations in Java. Check the following examples.

Example #1: Request Builder

Here is the simplest example of Builder pattern.

Let’s consider implementing a request sending package. We want to build the request step by step and then send it when the building is complete.

Request Class with Builder

package com.bigboxcode.designpattern.builder.request;

import java.util.HashMap;

enum RequestType {
    GET,
    POST,
    PUT,
    PATCH,
    DELETE,
}

public class Request {
    private String url;
    private RequestType type;
    private HashMap<String, String> header;
    private HashMap<String, String> body;

    private Request(Builder builder) {
        this.url = builder.url;
        this.type = builder.type;
        this.header = builder.header;
        this.body = builder.body;
    }

    public void send() {
        System.out.println("Sending Request...");
        System.out.println("URL: " + url);
        System.out.println("Type: " + type);
        System.out.println("Headers: " + header);
        System.out.println("Body: " + body);


        // Write functional code to send request
    }

    public static class Builder {
        private String url;
        private RequestType type;
        private HashMap<String, String> header = new HashMap<String,String>();
        private HashMap<String, String> body =new HashMap<String,String>();

        public Builder url(String url) {
            this.url = url;

            return this;
        }

        public Builder type(RequestType type) {
            this.type = type;

            return this;
        }

        public Builder header(String key, String value) {
            this.header.put(key, value);

            return this;
        }

        public Builder body(String key, String value) {
            this.body.put(key, value);

            return this;
        }

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

Demo

package com.bigboxcode.designpattern.builder.request;

public class Demo {
    public static void main(String[] args) {
        // Build the request step by step
        Request request = new Request.Builder()
                .url("https://bigboxcode.com/request-test")
                .type(RequestType.POST)
                .header("X-AUTH-TOKEN", "someTokeHere")
                .header("X-SOME-HEADER", "someRandomHeaderValueHere")
                .body("unit_id", "99")
                .body("code", "88C3ABK")
                .build();

        // Send request
        request.send();
    }
}

Output

Sending Request...
URL: https://bigboxcode.com/request-test
Type: POST
Headers: {X-SOME-HEADER=someRandomHeaderValueHere, X-AUTH-TOKEN=someTokeHere}
Body: {code=88C3ABK, unit_id=99}

Example #2: Vehicle Builder

Car Concrete Class

package com.bigboxcode.designpattern.builder.vechicle;

public class Car {
    private int wheel;
    private int engine;
    private int seat;
    private int door;

    private boolean interior;

    public Car(int noOfWheel, int noOfEngine, int noOfSeat, int noOfDoor, boolean interior) {
        this.wheel = noOfWheel;
        this.engine = noOfEngine;
        this.seat = noOfSeat;
        this.door = noOfDoor;
        this.interior = interior;
    }

    public int getWheel() {
        return wheel;
    }

    public int getEngine() {
        return engine;
    }

    public int getSeat() {
        return seat;
    }

    public int getDoor() {
        return door;
    }

    public boolean isInterior() {
        return interior;
    }

    public String toString() {
        return "Car: Wheel -> " + wheel + " | Engine -> " + engine + " | Seat -> " + seat + " | Door -> " + door + " | Interior -> " + interior;
    }
}

Plane Concrete Class

package com.bigboxcode.designpattern.builder.vechicle;

public class Plane {
    private int wheel;
    private int engine;
    private int seat;
    private int door;
    private int wing;

    private boolean interior;

    public Plane(int noOfWheel, int noOfEngine, int noOfSeat, int noOfDoor, int wing, boolean interior) {
        this.wheel = noOfWheel;
        this.engine = noOfEngine;
        this.seat = noOfSeat;
        this.door = noOfDoor;
        this.wing = wing;
        this.interior = interior;
    }

    public int getWheel() {
        return wheel;
    }

    public int getEngine() {
        return engine;
    }

    public int getSeat() {
        return seat;
    }

    public int getDoor() {
        return door;
    }

    public int getWing() {
        return wing;
    }

    public boolean isInterior() {
        return interior;
    }

    public String toString() {
        return "Plane: Wheel -> " + wheel + " | Engine -> " + engine + " | Seat -> " + seat + " | Door -> " + door + " | Wing: " + wing + " | Interior -> " + interior;
    }
}

Vehicle Builder Interface

package com.bigboxcode.designpattern.builder.vechicle;

public interface VehicleBuilder {

    void addWheel(int noOfWheel);

    void addEngine(int noOfEngine);

    void addSeat(int noOfSeat);

    void addInterior();

    void addDoor(int noOfDoor);

    void addWing(int noOfWing) throws Exception;



}

Car Builder Class

package com.bigboxcode.designpattern.builder.vechicle;

public class CarBuilder implements VehicleBuilder {
    private int wheel;
    private int engine;
    private int seat;
    private boolean interior;
    private int door;

    @Override
    public void addWheel(int noOfWheel) {
        System.out.println("Add " + noOfWheel + " wheels");

        this.wheel += noOfWheel;
    }

    @Override
    public void addEngine(int noOfEngine) {
        System.out.println("Add " + noOfEngine + " engine");

        this.engine += noOfEngine;
    }

    @Override
    public void addSeat(int noOfSeat) {
        System.out.println("Add " + noOfSeat + " Seat");

        this.seat = noOfSeat;
    }

    @Override
    public void addInterior() {
        System.out.println("Add interior");

        this.interior = true;
    }

    @Override
    public void addDoor(int noOfDoor) {
        System.out.println("Add " + noOfDoor + " door");

        this.door += noOfDoor;
    }

    @Override
    public void addWing(int noOfWings) throws Exception {
        throw new Exception("Can not add wings");
    }

    public Car build() {
        Car car = new Car(wheel, engine, seat, door, interior);

        return car;
    }

}

Plane Builder Class

package com.bigboxcode.designpattern.builder.vechicle;

public class PlaneBuilder implements VehicleBuilder {
    private int wheel;
    private int engine;
    private int seat;

    private boolean interior;
    private int door;
    private int wing;

    @Override
    public void addWheel(int noOfWheel) {
        System.out.println("Add " + noOfWheel + " wheels");

        this.wheel += noOfWheel;
    }

    @Override
    public void addEngine(int noOfEngine) {
        System.out.println("Add " + noOfEngine + " engine");

        this.engine += noOfEngine;
    }

    @Override
    public void addSeat(int noOfSeat) {
        System.out.println("Add " + noOfSeat + " Seat");

        this.seat = noOfSeat;
    }

    @Override
    public void addInterior() {
        System.out.println("Add interior");

        this.interior = true;
    }

    @Override
    public void addDoor(int noOfDoor) {
        System.out.println("Add " + noOfDoor + " door");

        this.door += noOfDoor;
    }

    @Override
    public void addWing(int noOfWings) throws Exception {
        System.out.println("Add " + noOfWings + " wing");

        this.wing += wing;
    }

    public Plane build() {
        Plane plane = new Plane(wheel, engine, seat, door, wing, interior);

        return plane;
    }

}

Vehicle Producer Class

package com.bigboxcode.designpattern.builder.vechicle;

public class VehicleProducer {
    public CarBuilder buildCar(CarBuilder carBuilder) {
        carBuilder.addWheel(4);
        carBuilder.addEngine(1);
        carBuilder.addDoor(4);
        carBuilder.addSeat(4);
        carBuilder.addInterior();

        return carBuilder;
    }

    public PlaneBuilder buildPlane(PlaneBuilder planeBuilder) {
        planeBuilder.addWheel(3);
        planeBuilder.addEngine(2);
        planeBuilder.addDoor(4);
        planeBuilder.addSeat(120);
        planeBuilder.addInterior();
        try {
            planeBuilder.addWing(2);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return planeBuilder;
    }
}

Demo

package com.bigboxcode.designpattern.builder.vechicle;

public class Demo {
    public static void main(String[] args) {
        VehicleProducer vehicleProducer = new VehicleProducer();

        System.out.println("Building Car:\n");

        CarBuilder carBuilder = new CarBuilder();
        vehicleProducer.buildCar(carBuilder);

        Car car = carBuilder.build();
        System.out.println("\nFinal result:\n" + car);

        System.out.println("----------------------------");

        System.out.println("Building Car:\n");

        PlaneBuilder planeBuilder = new PlaneBuilder();
        vehicleProducer.buildPlane(planeBuilder);

        Plane plane = planeBuilder.build();
        System.out.println("\nFinal result:\n" + plane);

    }
}

Output

Building Car:

Add 4 wheels
Add 1 engine
Add 4 door
Add 4 Seat
Add interior

Final result:
Car: Wheel -> 4 | Engine -> 1 | Seat -> 4 | Door -> 4 | Interior -> true
----------------------------
Building Car:

Add 3 wheels
Add 2 engine
Add 4 door
Add 120 Seat
Add interior
Add 2 wing

Final result:
Plane: Wheel -> 3 | Engine -> 2 | Seat -> 120 | Door -> 4 | Wing: 0 | Interior -> true

Source Code

Use the following link to get the source code:

Leave a Comment