Builder, as the name suggests builds complex objects from simple ones step-by-step. It separates the construction of complex objects from their representation.
Let’s take a non-software example for this. Say, we have to plan for a children meal at a fast food restaurant. What is it comprised of? Well, a burger, a cold drink, a medium fries and a toy.
This is common to all the fast food restaurants and all the children meals. Here, what is important? Every time a children’s meal is ordered, the service boy will take a burger, a fries, a cold drink and a toy. Now suppose, there are 3 types of burgers available. Vegetable, Fish and Chicken, 2 types of cold drinks available. Cola and Orange and 2 types of toys available, a car and a doll.
So, the order might be a combination of one of these, but the process will be the same. One burger, one cold drink, one fries and one toy. All these items are placed in a paper bag and is given to the customer.
Now let’s see how we can apply software to this above mentioned example.
The whole thing is called a children meal. Each of the four burger, cold drink, fries and toy are items in the meal. So, we can say, there is an interface Item having two methods, pack() and price().
Let’s take a closer look at the interface Item:
Item.java
| package creational.builder; public interface Item { | |
| | /** /** public int price(); |
| }// End of class | |
So, we must now have a class defined for each of the items, as burger, toy, cold drink and fries. All these will implement the Item interface.
Lets start with Burger:
Burger.java
| package creational.builder; | |
| | /** /** |
| }// End of class | |
The class Burger can be further extended to VegBurger, FishBurger, ChickenBurger etc. These classes will each implement the price() method and return a price for each type of burger. I, in this example have given the implementation for VegBurger class.
VegBurger.java
| package creational.builder; | |
| | /** |
| }// End of class | |
Let’s concentrate on other items now. I, here for explanation purpose will give another item Fries.
Fries.java
| package creational.builder; /** | |
| | /** /** |
| }// End of class | |
Now, let’s see the Builder class, MealBuilder. This class is the one which serves the Children’s meal.
MealBuilder.java
| package creational.builder; /** | |
| | public Packing additems() { return new MealBox().addItems(items); public int calculatePrice() { return totalPrice; |
| }// End of class | |
This class gives the total meal and also presents the total price. Here, we have abstracted the price calculation and meal package building activity from the presentation, which is a meal box. The Builder pattern hides the internal details of how the product is built.
Each builder is independent of others. This improves modularity and makes the building of other builders easy.
Because, each builder builds the final product step by step, we have more control on the final product.
Comments
Post a Comment