Builder Pattern

Builder pattern is a creational design pattern it means its solves problem related to object creation.

It allow construction of object in steps.

The same could be achieved by providing multiple constructors. Having multiple constructor will have following disadvantages:

  • When the object that needs to be created has many parameters, some of which are mandatory and some optional. Then we need to provide different overloaded constructors and even worst will accept many parameters.
  • The overloaded constructors may have many fields of same type which might be confusing.

Lets take the Pizza problem.

You can partially solve above problem by creating Pizza and then adding ingredients but that will impose another problem of leaving Object on inconsistent state during building, ideally Pizza should not be available until its created. This also requires a lot of extra effort to ensure thread safety.

BUILDER WAY:

BuilderPattern

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder’s setter methods return the Builder object they are able to be chained.

Pizza pizza = new Pizza.Builder(12).cheese(true).pepperoni(true).bacon(true).build();

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: