Builder Pattern

You must have used DocumentBuilder or StringBuilder classes if you have worked with core Java. Buider pattern is simple object creation pattern, which helps handling of creation of complex objects by breaking the object building exercise into multiple easy steps.

A simple example will be- let’s say we have a car object with many complex properties- Engine, top speed, boot_space, seating arrangement, air_conditioning etc. A CarBuilder class can help in creation of the objects

Class CarBuilder{

public void setEngine(Engine e)
{
//..
}

public void setSpeed(String s)
{
//..
}

public void setAirConditioning(String temp, String cooling, int avgtemp)
{
//..
}

public Car getCar()
{
//This will finally create the car object and return
}

}

The calling method

CarBuilder cB=new CarBuilder();
cB.setEngine(e);
//.so on
Car myCar=cB.getCar();

To make it more useful in handling higher complexity, we can create the CarBuilder as Abstract Class or interface, which is implemented by HatchBackBuilder, SportsCarBuilder etc.