Design Patterns - The Builder Pattern

Builder Pic

Intent

  • Separate the construction of a complex Object from it’s representation
  • Facilitate building complex objects where multiple parameters are involved

Problem

When you need flexibility while creating objects, Builder Pattern provides a pattern to creating particular representation of the complex object by encapsulating the object creation and assembling to separate class.

Solution

It provides Static Factory builder object to start and facilitates adding additional parameters.

Summary

  • Builder Design Pattern falls under Creational Pattern which facilitates flexibility and readability while creating multiple objects because same builder can be re-used.

Builder Pattern

Example

UserTest.java

package com.art.designpatterns.builder;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
class User {
    private String firstName;
    private String lastName;
    private String email;
    private String address;
}

/**
 * Demo Class
 */
class UserBuilderTest{
  public static void main(String[] args) {
    User johnDoe = new UserBuilder("John", "Doe").build();
    User robertNoyce = new UserBuilder("Robert", "Noyce")
                                .email("robert.noyce@gmail.com")
                                .address("Burlington, IA").build();
    System.out.println(johnDoe);
    System.out.println(robertNoyce);
  }
}

UserBuilder.java

package com.art.designpatterns.builder;

public class UserBuilder {

  private User user;

  //Required
  private String firstName;
  private String lastName;

  //Defaults
  private String email = "";
  private String address = "";

  /**
   * UserBuilder with firstName and lastName as required Parameters
   * @param firstName
   * @param lastName
   */
  public UserBuilder(String firstName, String lastName){
    this.firstName = firstName;
    this.lastName = lastName;
  }

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

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

  public User build(){
    user = new User();
    user.setFirstName(firstName);
    user.setLastName(lastName);
    user.setEmail(email);
    user.setAddress(address);

    return user;
  }
}