Skip to main content

Creational Patterns - Builder Pattern

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 {

 

/**
* pack is the method, as every item will be packed
* in a different way.
* E.g.:- The burger will be packed as wrapped in a paper
* The cold drink will be given in a glass
* The medium fries will be packed in a card box and
* The toy will be put in the bag straight.
* The class Packing is an interface for different types of
* for different Items.
*/

public Packing pack();

/**
* price is the method as all the items
* burger, cold drink, fries will have a price.
* The toy will not have any direct price, it will
* be given free with the meal.
*
* The total price of the meal will be the combined
* price of the three items.
*
* @return price, int in rupees.
*/

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;
/**
* The class remains abstract as price method will be implemented
* according to type of burger.
* @see price()
*
*/
public abstract class Burger implements Item {

 

/**
* A burger is packed in a wrapper. Its wrapped
* in the paper and is served. The class Wrapper is
* sub-class of Packing interface.
* @return new Wrapper for every burger served.
*/
public Packing pack() {
return new Wrapper();
}

/**
* This method remains abstract and cannot be
* given an implementation as the real implementation
* will lie with the type of burger.
*
* E.g.:- Veg Burger will have a different price from
* a fish burger.
*
* @return price, int.
*/
public abstract int price();

}// 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;

/**
* The implementation of price method.
*/
public class VegBurger extends Burger {

 

/**
* This is the method implementation from
* the super class Burger.
*
* @return price of a veg burger in rupees.
*/
public int price() {
return 39;
}

}// 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;

/**
* Implements the Item interface.
*/
public class Fries implements Item {

 

/**
* Packing in which fries are served.
*
* @return new Packing for every fries.
* Envelop is a packing in which fries are given
*/
public Packing pack() {
return new Envelop();
}

/**
* Price of the medium fries.
*
* @return int , price of medium fries in rupees
*/
public int price() {
return 25;
}

}// 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;

/**
* Main builder class which builds the entire meal
* for the customers
*/
public class MealBuilder {

 

public Packing additems() {
Item[] items = {new VegBurger(), new Fries(), new Cola(), new Doll()}

return new MealBox().addItems(items);
}

public int calculatePrice() {
int totalPrice = new VegBurger().price() + new Cola().price() + new Fries().price() + new Doll().price();

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

Popular posts from this blog

Java Health Center - Overview and Features

This video highlights the features available in Health Center. Health Center is a low-processor and memory usage diagnostic tool for monitoring the status of a running IBM Java Virtual Machine (JVM). Health Center provides live information and recommendations in each of the following areas: - Classes: information about classes being loaded - Environment: details of the configuration and system of the monitored application - Garbage Collection: information about the Java heap and pause times - Locking: information about contention on inflated locks - Profiling: sampling profile of Java methods including call paths

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag...

Java Garbage Collection

Explain Garbage collection mechanism in Java? Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic pro...