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.

Latest posts by Prasad Kharkar (see all)

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

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 *