Wednesday, 7 August 2013

Creational Design Patterns -> Builder pattern


Motivation:
This pattern allows a client object to construct a complex object by specifying only its type and content, being shielded from the details related to the object�s representation. This way the construction process can be used to create different representations. The logic of this process is isolated form the actual steps used in creating the complex object, so the process can be used again to create a different object form the same set of simple objects as the first one.

Intent:
•    Defines an instance for creating an object but letting subclasses decide which class to instantiate
•    Refers to the newly created object through a common inter

Unlike the abstract factory pattern  and the factory method pattern whose intention is to enable polymorphism, the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern.

Following problems will be solved by Builder:

Problems:
1) too many constructors to maintain.
2) error prone because many fields has same type e.g. sugar and and butter are in cups so instead of 2 cup sugar if you pass 2 cup butter, your compiler will not complain but will get a buttery cake with almost no sugar with high cost of wasting butter.

When to use Builder Design pattern in Java
Builder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don't confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class.


Advantages:
1) more maintainable if number of fields required to create object is more than 4 or 5.
2) less error-prone as user will know what they are passing because of explicit method call.
3) more robust as only fully constructed object will be available to client.

Disadvantages:
1)    verbose and code duplication as Builder needs to copy all fields from Original or Item class.


Example: StringBuffer, String Builder

Sources: Wikipedia, OODesign, TutorialsPoint, Javarevisited

No comments:

Post a Comment