This is the second pattern that I am going to discuss after Abstract Factory. Now, if you have read the description of this pattern, you will feel like it is similar to Abstract Factory pattern, but there is a difference in the way it is organized and where it should be used.
First, lets get the definition of the same.
Separate the construction of a complex object from its representation so that the same construction process can create different representations
Lets take an example. Lets say, we have to make a perfect husband using Builder pattern. It should be funny. It is a very detailed process which lot of attributes and qualities. It will be a step by step process. Now there will be different types of requirements for Husbands, hence the process will change depending on the qualities, attributes required. We will see the exact implementation of this pattern soon.
First, the difference between Builder and Abstract Factory. The core difference is that in Abstract Factory, no matter now complex the object (Husband) may be, it will not have a step by step process to create the end Product (a perfect husband). Abstract Factory will have a dedicated implementation of the different variations. Builder, we can define common standard qualities and attributes separate and have different processes to result in different variations of the end product (Husband).
Lets look at an example. I am currently in Seoul but back in India, I love Dominos Pizza that too “Cheese burst”. If you have gotten a taste of it, you’ll know what I mean. Anyway, lets start.
The core of this pattern start with “Product”. In our case, Pizza. This defines a simple product with options of base, toppings and cheese which are open for customization for different options.
The next component is the “Builder” which defines methods for creating pizza. This is an abstract class which will be used for various variety of pizza makes – Dominos, Pizzahut.
Now, the next two are the 2 different implementations of PizzaBuilder – Dominos and Pizzahut.
Now, the Director which controls to create a Pizza – automatic counter. Sets the make of the pizza and then builds the pizza based on the various options.
Finally the main class, which decides which pizza to make – will be the end user and calls the Director – AutomaticCounter which builds the pizza the delivers to main end user.
Hope you like the explanation and example used. Feel free to ask any questions or provide suggestion for improvement.
You can download the entire working eclipse project for this pattern from HERE.