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.

 

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.

Read Also:  Mark Cuban's Stunning Scoop on the GooTube Deal

Leave a Reply

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