Android – How to create an object by Builder pattern

How to create a class by Builder pattern like this

new User.Builder()
        .setFirstName("Leonardo")
        .setLastName("da Vinci")
        .setAge(67)
        .create();

Create Model

public class User {
    private String firstName;
    private String lastName;
    private int age;
}

Add Builder

public class User {
    
    ...

    static class Builder {
        private String firstName;
        private String lastName;
        private int age;

        public Builder setFirstName(final String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder setLastName(final String lastName) {
            this.lastName = lastName;
            return this;
        }

        public Builder setAge(final int age) {
            this.age = age;
            return this;
        }

        public User create() {
            // Uses constructor from User class and returns the User object — here is the place where our mess is kept hidden.
            return new User(this);
        }
    }
}

Add constructor

public class User {
    
    ...

    // User constructor is private, so it can’t be accessed from the other class and we must use Builder to create new object
    private User(final Builder builder) {
        firstName = builder.firstName;
        lastName = builder.lastName;
        age = builder.age;
    }

    ...
}

Make parameters required

...
public User create() {
    User user = new User(firstName, lastName, age);
    if (user.firstName.isEmpty()) {
        throw new IllegalStateException(
           "First name can not be empty!");
    }
    return user;
}
...

Tip: Auto generate Builder by IntelliJ

All you need to do is place the caret on the constructor in your class and choose Refactor -> Replace Constructor with Builder on the context menu. Builder class with all the methods will be auto generated, ready for use.

Be the first to comment

Leave a Reply

Your email address will not be published.


*