Java Builder Pattern

Creational pattern for constructing complex objects step by step

java (1.0+) 2025-11-03 builder design-pattern creational

Description

The Builder pattern provides a flexible solution to construct complex objects. It separates the construction of an object from its representation, allowing the same construction process to create different representations.

Key Benefits

  • Flexible construction: Build objects step by step
  • Readable code: Method chaining creates fluent interfaces
  • Optional parameters: Handle many optional parameters elegantly
  • Immutable objects: Can create immutable objects with many parameters
  • Validation: Validate parameters during construction

When to Use

  • Objects with many optional parameters
  • Need for immutable objects
  • Complex object construction
  • Want to avoid telescoping constructor anti-pattern
  • Need to validate parameters before object creation

Implementation Pattern

  • Static inner Builder class
  • Private constructor in main class
  • Builder methods return this for chaining
  • build() method creates and returns the object
  • Validation in build() method

Code

RAW
public class User {    private final String firstName;    private final String lastName;    private final int age;    private final String email;    private final String phone;        // Private constructor    private User(Builder builder) {        this.firstName = builder.firstName;        this.lastName = builder.lastName;        this.age = builder.age;        this.email = builder.email;        this.phone = builder.phone;    }        // Getters    public String getFirstName() { return firstName; }    public String getLastName() { return lastName; }    public int getAge() { return age; }    public String getEmail() { return email; }    public String getPhone() { return phone; }        // Builder class    public static class Builder {        private String firstName;        private String lastName;        private int age;        private String email;        private String phone;                // Required parameters        public Builder(String firstName, String lastName) {            this.firstName = firstName;            this.lastName = lastName;        }                // Optional parameters with fluent interface        public Builder age(int age) {            this.age = age;            return this;        }                public Builder email(String email) {            this.email = email;            return this;        }                public Builder phone(String phone) {            this.phone = phone;            return this;        }                // Build method with validation        public User build() {            if (firstName == null || lastName == null) {                throw new IllegalStateException("First name and last name are required");            }            if (age < 0) {                throw new IllegalStateException("Age cannot be negative");            }            return new User(this);        }    }}// Generic builder interfacepublic interface Builder<T> {    T build();}// Advanced builder with validationpublic class ProductBuilder implements Builder<Product> {    private String name;    private double price;    private String category;        public ProductBuilder name(String name) {        this.name = name;        return this;    }        public ProductBuilder price(double price) {        if (price < 0) {            throw new IllegalArgumentException("Price cannot be negative");        }        this.price = price;        return this;    }        public ProductBuilder category(String category) {        this.category = category;        return this;    }        @Override    public Product build() {        if (name == null) {            throw new IllegalStateException("Product name is required");        }        return new Product(name, price, category);    }}
RAW
// Basic usageUser user1 = new User.Builder("John", "Doe")    .age(30)    .email("[email protected]")    .phone("123-456-7890")    .build();// Minimal required parametersUser user2 = new User.Builder("Jane", "Smith")    .build();// With some optional parametersUser user3 = new User.Builder("Bob", "Johnson")    .email("[email protected]")    .build();// Method chaining is readableUser user4 = new User.Builder("Alice", "Williams")    .age(25)    .email("[email protected]")    .phone("555-1234")    .build();// Product builder usageProduct product = new ProductBuilder()    .name("Laptop")    .price(999.99)    .category("Electronics")    .build();// Validation exampletry {    User invalid = new User.Builder("Test", "User")        .age(-5) // Will throw exception in build()        .build();} catch (IllegalStateException e) {    System.out.println("Validation failed: " + e.getMessage());}

Comments

No comments yet. Be the first to comment!