Monday, January 19, 2015

Builder Design Pattern

Type : Creational Design Pattern


Summary :


Builder pattern is a Creational Design Pattern and solves the problem of creating complex objects or objects whose constructor needs many parameters.
Considering a Class whose constructor has a number of parameters, we have to send all of them to instantiate an instance, which could be error prone and complex sometimes.
Also if the constructor has some optional parameters or if we want to have some parameters to have fixed value, we might end up with a number or Constructors for the object.


Advantages:

Reduces the number of constructor by using another object.
Increases the readability of the code and less error prone in passing parameters of same type to the constructor.


Disadvantages:

Code duplication as Builder Class needs to copy all the fields from the target object.

Example:

For our example we will consider a Class BlogObject which represents a Blog and has a number of fields. Some of the fields like, Tag, Summary etc are optional. Without Builder we might need to have a number of constructors for the Class. But with Builder we can create the instance of the Object easily and efficiently.

Class Diagram:



Java Code:




1 comment :