Table of Contents

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 ?

  • In Java for instance, with multiple constructor, you need to have the keyword this in the first place. You cannot then have a constructor with a path to a inputstream constructor that doesn't send a exception. Why ? because you need first to transform a path into a input stream and this operations sends an exception that you need to handle.

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