Builder Pattern

Builder Pattern is a creational pattern that builds a complex object using step by step approach. The builder class itself is independent of other objects. Builder pattern is similar to Abstract Factory Pattern. The only big difference between them is that builder provides more control over the object creation process. In one sentence, abstract factory pattern is the answer to “WHAT” and the builder pattern is the answer to “HOW”. Also, Builder Pattern is very helpful in creating immutable objects in an application.

In example shown above an object of class User is created. Two fields (firstName and lastName) are mandatory and other three fields are optional. Using Builder Pattern is elegant approach, reducing boilerplate code and providing objects immutability.

Step 1 : Create User class and UserBuilder as User’s static class

public class User {
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;

private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}

// All Getters, but No Setters to provide immutability
public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

public int getAge() {
return age;
}

public String getPhone() {
return phone;
}

public String getAddress() {
return address;
}

@Override
public String toString() {
return "User{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
'}';
}

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

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

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

public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}

public UserBuilder address(String address) {
this.address = address;
return this;
}

// Return the finally constructed User object
public User build() {
User user = new User(this);
return user;
}
}
}

Step 2 : Demonstration of using Builder Pattern

public class BuilderPatternDemo {
public static void main(String[] args) {
User user1 = new User.UserBuilder("John", "Smith")
.age(30)
.phone("1234567")
.address("Some Address")
.build();

System.out.println(user1);
}
}

Note that an object created on Step 2 is immutable. There is no way to change its state, but creating a new one and making the same link to point to a newly created object.

The output will be :

User{firstName='John', lastName='Smith', age=30, phone='1234567', address='Some Address'}

Leave a Reply

Your email address will not be published. Required fields are marked *