Builder Design Pattern solves the problem of constructing complex objects. In simple words, a situation when a class is having complex constructors or multiple numbers of parameters, it really becomes difficult to create objects in the same manner as the parameters are defined.

Builder pattern solves the above problem through handling the situation by an object, rather than the multiple numbers of parameters. The Java uses the Builder pattern extensively. For example StringBuilder, Documentbuilder, StringBuffer and etc.

When to use the Builder design pattern.

  • In the case of constructing a large object, the builder pattern helps by slicing the operations of object creation.
  • We need instances to do specific tasks as per the requirement.
  • When we need to create an immutable class.
  • When there are multiple parameterized constructors.
  • In a situation when there are optional parameters available in the class which is not required to send from the client while creating the object.

Example of Basic Builder Class.

In the below class, MobileBuilder is a builder class for the mobile object which is having some required attributes and as well as optional attributes. As we are not defining any setter methods in the below class so we are getting the immutability state here. The below example builder class is returning the mobile object by easying the complex process of object creation.

public static class MobileBuilder {
    private final String model; //required
    private final String os; //required
    private int price;//optional

    public MobileBuilder(String model, String os) {
      this.model = model;
      this.os = os;
    }

    public MobileBuilder price(int price) {
      this.price = price;
      return this;
    }

    // Returning the final object.
    public mobile build() {
      mobile mobileobj = new mobile(this);
     return obj;
    }
  }
}

Use-case of Builder Design Pattern.

Let us consider a situation in which an eCommerce website wants to ask the customer’s personal information. So, the customer is provided with a form that has a different number of questions, of which the only name is mandatory.

The website wants to store this information in an immutable object. We can save this information by directly calling the constructor, but the form has multiple questions and being a customer can choose to answer only some of them.

So it will not be a logical approach to create the constructor with different combinations, and this can be solved by using the Builder pattern like below.

In the Below class CustomerForm.java , there is a static inner class that will act as a Builder. Outer class is having a constructor which accepts the builder object and initialize the class parameters.

The inner class CustomerFormBuilder.java has one public constructor which is having only required parameters as arguments. This class has a separate method add() for each of the optional parameters which will set the parameter value to the object.

package builderpattern;

public class CustomerForm {
  private String name; // required
  private String age; // optional
  private String gender; // optional
  private String customerType; // optional

  private CustomerForm(CustomerFormBuilder builder) {
    this.name = builder.name;
    this.age = builder.age;
    this.gender = builder.gender;
    this.customerType = builder.customerType;
  }

  @Override
  public String toString() {
    return " Name=" + name + "\n age=" + age + "\n gender=" + gender + "\n CustomerType=" + customerType;
  }

  public static class CustomerFormBuilder {
    private String name;
    private String age;
    private String gender;
    private String customerType;

    public CustomerFormBuilder(String Name) {
      this.name = Name;
    }

    public CustomerFormBuilder addAge(String age) {
      this.age = age;
      return this;
    }

    public CustomerFormBuilder addGender(String gender) {
      this.gender = gender;
      return this;
    }

    public CustomerFormBuilder addcustomerType(String customertype) {
      this.customerType = customertype;
      return this;
    }

    public CustomerForm build() {
      return new CustomerForm(this);
    }
  }
}

Below class is the implementation of the Builder class which calls the constructor of the CustomerFormBuilder class and passes the arguments through the constructor.

public class BuilderImplementaion {

  public static void main(String[] args) {
    CustomerForm customerData = new CustomerForm.CustomerFormBuilder("Ramesh") // required parameters
        .addAge("20") // optional
        .addGender("M") // optional
        .addcustomerType("Prime").build(); // to get back customer information
    System.out.println(customerData);
  }
}

Advantages of Builder Pattern.

  • Easily maintainable if the number of required fields to generate the object are high.
  • The final object is available for the client, this provides the robustness to the application.
  • Testing is easy with this approach.
  • Due to the isolated construction process, it is easy to modify or maintain.
  • Reduces the complexity of the object creation and produces the final created object.

Disadvantages of Builder Pattern.

  • This approach is not to go within the case of small applications.
  • It leads to code duplicity as the builder class copies all the items from the original item calls. Which results in low- performance output.
By |Last Updated: May 9th, 2020|Categories: Java™|