Tuesday, July 1, 2014

Builder Design Pattern in Java

INTRODUCTION

In the real world, a product built with two or more parts which may be complex or simple in nature. The builder pattern helps to build a complex product by building it's parts (may be simple) one by one (should maintain the order).

USECASE

Assembling a bike with its components like Engine, Wheel, and Gear etc.,

IMPLEMENTATION

Lets us create Model Class - Bike.
public class Bike {

 private String wheelType;
 private String engineType;
 private int cost;
 //getters and setters
}


The process of assembling a new bike will have set of activities. So my Builder class will have the following activities.

public interface BikeBuilder {
 void assembleEngine();
 void assembleWheel();
 void estimateCost();
 Bike getBike();
}

Now implement the BikeBuilder and create different bikes like HeroBike, RoyalEnfield Bike.

public class HeroBike implements BikeBuilder {

 private Bike bike;

 HeroBike() {
   bike = new Bike();
 }

 @Override
 public void assembleWheel() {
   bike.setWheelType("Alloy");
 }

 @Override
 public void estimateCost() {
   bike.setCost(50000);
 }

 @Override
 public void assembleEngine() {
   bike.setEngineType("Petrol");
 }

 @Override
 public Bike getBike() {
   return bike;
 }
}

Actually, the assembling of a bike will be done in a factory where the activities have done one by one sequentially. So create a factory.

public class BikeFactory {
 public void assemble(BikeBuilder bikeAssembler) {
   bikeAssembler.assembleWheel();
   bikeAssembler.assembleEngine();
   bikeAssembler.estimateCost();
 }
}

Now time to test the builder pattern.

public class BuilderPatternTest {

 public static void main(String[] args) {
   BikeBuilder assembler = null;
   BikeFactory bikeFactory = new BikeFactory();

   // Hero Bike
   System.out.println("=========HERO BIKE======");
   assembler = new HeroBike();
   bikeFactory.assemble(assembler);
   Bike heroBike = assembler.getBike();
   System.out.println("Cost: " + heroBike.getCost());
   System.out.println("Engine Type: " + heroBike.getEngineType());

   // Yamaha Bike
   System.out.println("=========ROYAL ENFIELD BIKE=====");
   assembler = new RoyalEnfield();
   bikeFactory.assemble(assembler);
   Bike yamahaBike = assembler.getBike();
   System.out.println("Cost: " + yamahaBike.getCost());
   System.out.println("Engine Type: " + yamahaBike.getEngineType());
 }
}

OUTPUT

=========HERO BIKE===============
Cost: 50000
Engine Type: Petrol

=========ROYAL ENFIELD BIKE===============
Cost: 170000
Engine Type: Diesel

Complete Source Code

Hope this example clarifies the Builder Design Pattern. Please share your thoughts in the comments box.
Happy Knowledge Sharing!!!

No comments :

Post a Comment