Wednesday, May 25, 2016

Builder Design Pattern tutorial example java

As the name suggest it self that builds complex objects from simple one step by step and the object creation process should be generic So that it can be used to create different representations of the same object.
eg. A car is the final product(Object) that is returned to be output but as you know there are lots of other steps to create car.

When to use Builder Pattern?
When you wants to hide the internal details of how the product is built.each builder is independent of others.So each builder builds the final product step by step.This improves the modularity of builders.

In java ,String Buffer and String Builder are example of the builder pattern.

Example:
public interface CarPlan{
public void setWheels(String wheel);
public void setEngine(String engine);
}
public class Car implements CarPlan
{
  private String wheels;
  private String Engine;

 public void setEngine(String e)
 {
    this.Engine=e;
 }
 public void setWheel(String w)
this.wheels=w;
}
}
public interface CarBuilder
{
  public void buildWheels();
 public void buildEngine();
}
public LowPriceCar implements CarBuilder
{
  private Car car;
 public LowPriceCar()
 { 
   car =new Car();
 }
public void buildWheels()
{
 car.setWheels("Cheap Wheels")
}
public void buildEngine()
{
 car.setEngine("Cheap Engine")
}
pubic Car getCar(){ retrun this.car;}
}
public class HighEndCar implements CarBuilder
{
  private Car car;
  public HighEndCar()
  {
  car =new Car();
  }
 public void buildWheels()
 {
   car.setWheels("Quality wheels");
 }
 public void buildEngine()
{
  car.setEngine("High Quality Engine");
}
pubic Car getCar(){ retrun this.car;}

}

class MechanicalEngineer
{
  private CarBuilder carBuilder;
  public MechanicalEngineer(CarBuilder carBuilder){ this.carBuilder=carBuilder;}
  pubic Car getCar(){ retrun this.car;}
   public void buildCar()
  {
    carBuilder.buildWheels();
   carBuilder.buildEngine();

  }

}

Now test it main class

int main()
{
  CarBuilder lowPriceCar= new LowPriceCar();
 MechanicalEngineer engineer=new MechanicalEngineer(lowPriceCar);
 engineer.buildCar();

Car car =engineer.getCar();
System.out.println("Builder Constructed Car:" + car);
}

No comments: