Monday, March 5, 2012

Creational Patterns - 3.Builder Pattern

When dealing with the construction of complex objects,there always should be a consideration of builder pattern. This pattern abstracts the construction steps for an object. Different builders can implement the steps on their own way.

There is one more component called Director takes care of driving the builder for constructing an object.

Example Use Case:-

This use case involves the process of constructing a house.

Construction steps for a house may contain the following things,


  • Flooring
  • Wall construction
  • Roofing
We are going to construct,

  1. CountryTiledHouse
  2. TerraceHouse
Both the above mentioned houses are having their own styles for flooring,wall,roof,etc.

Here, we are going to abstract the construction process of the floor,wall and roof.

So that, different types of houses can construct them as per their taste.

Following class diagram will clearly explain the design approach,




The flow of constructing a CountryTiledhouse can be specified as follows,
1) Initialize our builder,

HouseBuilder houseBuilder=new TileHouseBuilder();

2) Ask the director to use the builder,

BuildingDirector director=new BuildingDirector(houseBuilder);


3) Ask the director to build the house

director.buildHouse();

4) Request the house from the builder after being built based on the director's instructions

System.out.println(houseBuilder.getHouse().getFloor());

If we need a TerraceHouse, we just need to change the builder as follows,

HouseBuilder houseBuilder=new TerraceBuilder();

No comments:

Post a Comment