stock market

Builder Design Pattern Tutorial with Practical Examples in Java

Spread the love
1. What is a Design Pattern.

design pattern is a proven, reusable solution to a commonly occurring software design problem. It represents best practices developed by experienced software developers to solve recurring problems in object‑oriented design.

2. What is builder design pattern ? .

In builder design pattern we removed the logic related to object constructor from client code & abstract it in separate class.

This pattern was introduced to solve some of the problems with factory design pattern when the object contains a lot of attributes . major issues with factory design pattern is when object contains a lot of attributes.

Some of the parameters might be optional but in factory pattern. we are forced to send all the parameters and optional parameters need to send as Null.

3. Structure of Builder Pattern
It has 4 main parts:
  1. Product → Final object (Car, User)
  2. Builder → Builds the object step-by-step
  3. Fluent Methods → Chainable setters
  4. Build Method → Returns final object

4. Example : Builder design pattern Implementation

1.Car.java

public class Car {

    // Required parameters
    private String engine;
    private int wheels;

    // Optional parameters
    private boolean sunroof;
    private boolean airConditioner;
    private String color;

    // Private constructor
    private Car(Builder builder) {
        this.engine = builder.engine;
        this.wheels = builder.wheels;
        this.sunroof = builder.sunroof;
        this.airConditioner = builder.airConditioner;
        this.color = builder.color;
    }

    // Static inner Builder class
    public static class Builder {

        // Required parameters
        private String engine;
        private int wheels;

        // Optional parameters - initialized with default values
        private boolean sunroof = false;
        private boolean airConditioner = false;
        private String color = "White";

        // Constructor with required parameters
        public Builder(String engine, int wheels) {
            this.engine = engine;
            this.wheels = wheels;
        }

        // Setter methods for optional parameters
        public Builder setSunroof(boolean sunroof) {
            this.sunroof = sunroof;
            return this;
        }

        public Builder setAirConditioner(boolean airConditioner) {
            this.airConditioner = airConditioner;
            return this;
        }

        public Builder setColor(String color) {
            this.color = color;
            return this;
        }

        // Build method to create object
        public Car build() {
            return new Car(this);
        }
    }

    @Override
    public String toString() {
        return "Car [engine=" + engine +
               ", wheels=" + wheels +
               ", sunroof=" + sunroof +
               ", AC=" + airConditioner +
               ", color=" + color + "]";
    }
}

2. Main.java

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

        Car car = new Car.Builder("V8 Engine", 4)
                        .setSunroof(true)
                        .setAirConditioner(true)
                        .setColor("Black")
                        .build();

        System.out.println(car);
    }
}
Fashion Basket Silk Wine Embroidered Kurta Set with Duptta for Women
Amazon
  • Kurta Fabric And Work :- Chinon With Embroidered Work
  • Bottom Fabric And Work :- Silk Fabric With Embroidered Work
  • Duptta Fabric And Work :- Chinon Fabric With Embroidered Lace Border Work
We earn a commission if you make a purchase, at no additional cost to you.
4. Real Industry Use Cases using Builder Design pattern
  1. Banking System

Creating a Loan Object:

Loan loan = new LoanBuilder("Home Loan")
                .setInterestRate(7.5)
                .setTenure(25)
                .setInsurance(true)
                .build(); 

2.REST API Request Objects

Spring boot Microservices

UserRequest request = UserRequest.builder()
        .name("Rakesh")
        .email("test@gmail.com")
        .phone("9999999999")
        .address("Mumbai")
        .build();
3. Why Builder Pattern is Used in Real Projects

Avoid Constructor Confusion : No need to remember parameter order

Immutable Objects : Object becomes final after build()

Easy to Extend : Add new optional fields without breaking code

4. Builder Design Pattern Interview Questions

1. When should you use the Builder Pattern?

  • Many optional parameters
  • Complex object creation
  • Need for readable and maintainable code

2. What is the difference between Builder Pattern and Constructor?

  • Constructor → fixed parameters
  • Builder → flexible & readable

3. Is Builder Pattern immutable?

  • Yes (if designed properly)
  • Object is created only via build()

4. What are the main components of Builder Pattern?

  • Product (e.g., Car)
  • Builder (static inner class)
  • Build method

5. Have you used Lombok Builder?

@Builder
public class User {
private String name;
private String email;
}
Miss Ethnik Women's Maroon Faux Georgette Stitched Top with Stitched Faux Georgette Bottom
Amazon
  • Top fabric : faux georgette with santoon inner || bottom fabric : faux georgette with santoon inner || dupatta fabric : faux georgette
  • Work : embroidered || type : kurta palazzo set
  • Please read the products description below for full details of the product
We earn a commission if you make a purchase, at no additional cost to you.

6. Add validation in Builder Pattern

public Car build() {
if(engine == null) {
throw new IllegalStateException("Engine is required");
}
return new Car(this);
}

Leave a Reply

Your email address will not be published. Required fields are marked *