Builder Design Pattern

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Going forward with our design pattern tutorials, we will see yet another creational design pattern i.e. builder design pattern.

Builder Design Pattern:

Builder design pattern allows the client to create object based only on type of object. Gang of Four book defines builder design pattern as follows.

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Builder design pattern can roughly be drawn like below

Builder Design Pattern

Components in builder design pattern:

  • Product: Actual complex object that is going to be created.
  • Builder: Abstract class which declares abstract methods to construct object.
  • ConcreteBuilder: Provides actual implementation for creation of complex object.
  • Director: Invokes Builder methods for creation of object.

Consider our vehicle example again.

  • Vehicle is the object that we want to be created.
  • VehicleBuilder is abstract class which declares abstract behaviour.
  • BikeBuilder is concrete class which implements behaviour of VehicleBuilder in bike specific way.
  • CarBuilder is concrete class which implements behaviour of VehicleBuilder in car specific way.
  • VehicleManufacturer is Director.

Builder Design Pattern Implementation:

If you have git installed, then you can directly clone the design-patterns repository. I have kept code for all design patterns at https://github.com/theJavaGeek/design-patterns. Each branch is a different design pattern.

Go to your working directory and then follow below steps:

  1. git clone https://github.com/theJavaGeek/design-patterns.
  2. cd design-patterns
  3. git checkout builder

If you don’t have git installed, you can either directly download zip or copy paste from below.

Vehicle.java

VehicleBuilder.java

BikeBuilder.java

CarBuilder.java

VehicleManufacturer.java

Client.java

After running program, you will see

Installing bike engine
Installing two tyres
Installing Car engine
Installing four tyres
Vehicle [tyres=2, engine=Small Engine]
Vehicle [tyres=4, engine=High performance Engine]

Here is how it works.

  • VehicleManufacturer defines a createVehicle() method which is responsible for calling VehicleBuilder methods.
  • Client instantiates BikeBuilder and CarBuilder and passes to createVehicle() method.

Builder design pattern implementation for given code is depicted below.

Builder design pattern class diagram

I hope the article helped understand the concept of builder design pattern in java. In next article we will go through prototype pattern.

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *