0
0
JavaConceptBeginner · 4 min read

Builder Pattern in Java: What It Is and How It Works

The builder pattern in Java is a design pattern that helps create complex objects step-by-step using a separate Builder class. It allows you to build objects with many options clearly and safely without needing many constructors or confusing parameters.
⚙️

How It Works

The builder pattern works like assembling a custom sandwich at a deli. Instead of ordering a fixed sandwich, you pick each ingredient one by one until your sandwich is just right. Similarly, the builder pattern lets you set each part of an object separately, then finally build the complete object.

In Java, this means you have a Builder class with methods to set each property. These methods return the builder itself, so you can chain calls smoothly. When you finish setting all properties, you call a build() method that creates the final object with all the chosen options.

This approach avoids having many constructors with different parameters and makes the code easier to read and maintain.

💻

Example

This example shows a Pizza class built using the builder pattern. You can choose size, cheese, pepperoni, and bacon toppings step-by-step.

java
public class Pizza {
    private final String size;
    private final boolean cheese;
    private final boolean pepperoni;
    private final boolean bacon;

    private Pizza(Builder builder) {
        this.size = builder.size;
        this.cheese = builder.cheese;
        this.pepperoni = builder.pepperoni;
        this.bacon = builder.bacon;
    }

    public static class Builder {
        private final String size; // required
        private boolean cheese = false;
        private boolean pepperoni = false;
        private boolean bacon = false;

        public Builder(String size) {
            this.size = size;
        }

        public Builder cheese(boolean value) {
            this.cheese = value;
            return this;
        }

        public Builder pepperoni(boolean value) {
            this.pepperoni = value;
            return this;
        }

        public Builder bacon(boolean value) {
            this.bacon = value;
            return this;
        }

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

    @Override
    public String toString() {
        return "Pizza size: " + size + ", cheese: " + cheese + ", pepperoni: " + pepperoni + ", bacon: " + bacon;
    }

    public static void main(String[] args) {
        Pizza pizza = new Pizza.Builder("Large")
                .cheese(true)
                .pepperoni(true)
                .bacon(false)
                .build();
        System.out.println(pizza);
    }
}
Output
Pizza size: Large, cheese: true, pepperoni: true, bacon: false
🎯

When to Use

Use the builder pattern when you need to create objects that have many optional parts or configurations. It helps avoid constructors with many parameters, which can be confusing and error-prone.

For example, when creating complex objects like configuration settings, UI components, or data models with many optional fields, the builder pattern makes your code cleaner and easier to understand.

It is also useful when you want your object creation code to be readable and maintainable, especially if the object has many variations.

Key Points

  • The builder pattern separates object construction from its representation.
  • It uses a builder class with methods to set each property.
  • Allows chaining methods for clear and readable code.
  • Helps avoid many constructors with different parameters.
  • Ideal for creating complex objects with optional fields.

Key Takeaways

The builder pattern simplifies creating complex objects with many options.
It improves code readability by chaining setter methods in a builder class.
Use it to avoid constructors with many parameters and improve maintainability.
The final object is created only when build() is called, ensuring completeness.
Ideal for objects with optional or varying fields.