8/4/17

Builder Design Pattern

What Builder Design Pattern is :-


Builder is creational design pattern. It is used to create complex object with too many properties required for object creation, let's say 20-25 properties, out of those properties say 5 are mandatory and others are optional.

Builder pattern provides safety by passing required parameters in constructor and readability by setting optional parameters using setter methods.

Client calls constructor with all required parameters and gets Builder object. Then sets optional parameters using setter methods with choice. Finally calls build method to generate immutable object.

Where to use :-


A good use case would be object of Airplane. Airplane object will be having large no of properties.
And for Airplane to function you may not need all properties so there will be some mandatory and many optional properties.


How to use :-


Elements of Builder pattern are

  1. MyObject class with mandatory and optional properties.
  2. A member public static builder class
  3. Private constructor taking Builder as argument. 


public class MyObject {

 // 1st member - properties
 private final String propReq1;
 
 private final String propReq2;
 
 private final String propOpt1;
 
 private final String propOpt2;
 
 private final String propOpt3;
 
 
 // 2nd member public static Builder class
 public static class Builder {
 
  private final String propReq1;
  
  private final String propReq2;
  
  private String propOpt1 = "";
  
  private String propOpt2 = "";
  
  private String propOpt3 = "";
  
  public Builder(String propReq1, String propReq2) {
   this.propReq1 = propReq1;
   this.propReq2 = propReq2;
  }
  
  public Builder propOpt1(String propValue) {
   propOpt1 = propValue;
   return this;
  }
  
  public Builder propOpt2(String propValue) {
   propOpt2 = propValue;
   return this;
  }
  
  public Builder propOpt3(String propValue) {
   propOpt3 = propValue;
   return this;
  }
  
  public MyObject build() {
   return new MyObject(this);
  }
 
 }
 
 // 3rd memeber is private constructor taking builder as arument 
 private MyObject(Builder builder) {
  propReq1 = builder.propReq1;
  propReq2 = builder.propReq2;
  propOpt1 = builder.propOpt1;
  propOpt2 = builder.propOpt2;
  propOpt3 = builder.propOpt3;
 }
}


Using Builder

MyObject obj = MyObject.Build("one","two").propOpt1("three").propOpt2("four").propOpt3("five").build();

You can also impose validation on parameters while creating Final object from Builder object.