Builder design pattern

Have you ever created an object that has over 20 fields ?, have you ever tried to create this object using it’s constructor with several lines of code ? Have you ever needed to create an object without knowing its exact number of fields ? no worries, meet the Builder design pattern. 

Builder design pattern is an awesome pattern that eases the construction of complex objects.

Why Builder Patter ? 

Telescoping Constructor

Telescoping constructor is an anti-pattern that represents an object with several constructors each with different number of parameters. 

The problem with this telescoping constructor is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation. 

Objects default Values. 

Sometimes we create objects and we are concerned only with few fields, the rest is set to some default values. This pattern is most common in testing. In this case Builder design pattern helps a lot. 

Creating Object in Natural Language

Builder pattern helps building objects in natural language style, which really helps understanding the object’s complex parts during creation.

Not only one way to implement builder design pattern. 

As I mentioned previously, there is no one way to implement a design pattern. It is the idea behind the pattern that matters. 

Builder design pattern

Builder design pattern

The above design patter is described in GoF design patterns. 

The most used form of builder pattern, as some call it, the fluent builder. 

fluent-builder

fluent-builder

 

Where to use Builder design pattern

  • When the algorithm for creating a complex object should be independent of
    the parts that make up the object and how they are assembled.
  • When the construction process must allow different representations for the
    object that is constructed.
  • When you want to insulate clients from the knowledge of the actual
    creation process and/or resulting product.
  • When your object contains Telescoping constructors 
  • When you are concerned with only few properties of the object and the rest can be set to default. 

Drawbacks/consequences

  • Need flexibility in creating various complex objects. Need to create complex,
    aggregate objects 
  • It is time consuming and overhead to create builders. 

Examples from Java 

 

 

Facebooktwittergoogle_pluslinkedinFacebooktwittergoogle_pluslinkedin

Leave a comment

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