Sunday, March 8

Builder pattern for creating object : Creational Pattern

There are number of creational patterns which are use to create instances of class, but were builder pattern fit in and stand out from other creational pattern like static factory, telescoping constructor, javabean pattern and other's. Is its ability to scale with a large number of parameters. So let's get started with an example.


Let's consider a case where we have to create object of a Product class with several field like name, description, sellPrice, costPrice, maxRetailPrice, discount and brand. For selling a product name, sellPrice and description are mandatory field, a product object is incomplete without these three information.So we are going to implement builder pattern in this case to incur the problem.

Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Finally, the client calls a parameterless build method to generate the object, which is immutable. The builder is a static member class of the class it builds.

Now we look at client code (or calling code).


For more in on the topic refer to : 
  • Design Patterns: Elements of Reusable Object-Oriented Software aka Gang of Four (GOF).
  • Effective Java by Joshua Bloch

No comments:

Post a Comment

Ads Inside Post