Table of Contents

Design Pattern - (Object) Builder

About

The intent of the Builder design pattern is to separate the construction of a complex object from its representation.

Same idea than a Design Pattern - (Static) Factory

Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

The builder uses the Fluent Interface idiom to make the client code more readable

Why ?

Example

The class with a builder

public class User {
    private final String firstName; // required
    private final String lastName; // required
    private final int age; // optional
    
    private User(UserBuilder builder) {
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.age = builder.age;
    }

    public static class UserBuilder {
        private final String firstName;
        private final String lastName;
        private int age;

        public UserBuilder(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public UserBuilder age(int age) {
            this.age = age;
            return this;
        }
       
        public User build() {
            return new User(this);
        }

    }
}

The construction

User user =  new
                User.UserBuilder("Nico", "Gerard")
                .age(41)
                .build();

Documentation / Reference