Design Pattern - (Object) Builder

> Code - (Programming|Computer) Language > Design Pattern

1 - About

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

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

Advertising

3 - 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.

4 - Example

4.1 - 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);
        }
 
    }
}

4.2 - The construction

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

5 - Documentation / Reference

code/design_pattern/builder.txt · Last modified: 2017/09/20 22:34 by gerardnico