I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Design Patterns Uncovered: The Builder Pattern

06.15.2010
| 13750 views |
  • submit to reddit

Today's pattern is the Builder pattern,which allows for dynamic creation of objects based upon interchangable algorithms. 

Builder in the Real World 

The purpose of the builder pattern is to separate the construction of a complex object from its representation. so that the same construction process can create different representation. An example of this is happy meals at a fast food restaurant. The happy meal typically consists of a hamburger, fries, coke and toy. No matter whether you choose different burgers/drinks, the construction of the kids meal follows the same process.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Builder Pattern

The Builder is a creational pattern - it's used to construct objects such that they can be decoupled from the implementing system. The definition of Builder provided in the original Gang of Four book on Design Patterns states: 

Allows for object level access control by acting as a pass through entity or a placeholder object. 

Let's take a look at the diagram definition before we go into more detail.



The Builder provides an interface for creating the parts that make up a Product, and ConcreteBuilder provides an implementation of this interface.
The ConcreteBuilder keep track of the representation it creates, provides a way to get the result (Product) as well as constructing the product.
The Director constructs the object through the Builder's interface. The Product is the object, usually complex, that we are constructing. This would include all the classes that define what we are constructing.

The builder pattern will typically use other creational patterns to get products built (e.g. Prototype or Singleton) and will often build a composite.

Would I Use This Pattern?

This pattern is used when object creation algorithms should be decoupled from the system, and multiple representations of creation algorithms are required. This decoupling is useful as you can add new creation functionality to your system without affecting the core code. You also get control over the creation process at runtime with this approach.

An example of the pattern in the Java API would the StringBuilder append method. 

So How Does It Work In Java?

We'll continue with our meals example from earlier.
First, we have the concept of a meal builder, that puts together the parts : main, drink and dessert. The Meal is the composite product that holds all the relevant parts. 

		  
// Builder
public abstract class MealBuilder {
protected Meal meal = new Meal();
public abstract void buildDrink();
public abstract void buildMain();
public abstract void buildDessert();
public abstract Meal getMeal();
}

Next we create two specific builders, one for kids, one for adults:




public class KidsMealBuilder extends MealBuilder {
public void buildDrink() {
// add drinks to the meal
}
public void buildMain() {
// add main part of the meal
}
public void buildDessert() {
// add dessert part to the meal
}
public Meal getMeal() {
return meal;
}
}

public class AdultMealBuilder extends MealBuilder {
public void buildDrink() {
// add drinks to the meal
}
public void buildMain() {
// add main part of the meal
}
public void buildDessert() {
// add dessert part to the meal
}
public Meal getMeal() {
return meal;
}
}

In order to kick off the build process, we have a director: 

	// Director
public class MealDirector {
public Meal createMeal(MealBuilder builder) {
builder.buildDrink();
builder.buildMain();
builder.buildDessert();
return builder.getMeal();
}
}

And finally we have a client to run all of this:

	// Integration with overal application
public class Main {
public static void main(String[] args) {

MealDirector director = new MealDirector();
MealBuilder builder = null;

if (isKid)
builder = new KidsMealBuilder();
} else
{
builder = new AdultMealBuilder();
}
Meal meal = director.createMeal(mealBuilder);
}
}

Watch Out for the Downsides

There's not many downsides that I see to the builder. The decoupling is useful, but the switch statements necessary when using the pattern on it's own aren't very appealing. As with all patterns, it adds complexity when used in the wrong places.

Other Articles in This Series
The Observer Pattern
The Adapter Pattern
The Facade Pattern
The Factory Method Pattern
The Abstract Factory Pattern
The Singleton Pattern
The Strategy Pattern
The Visitor Pattern

The Decorator Pattern
The Proxy Pattern
The Command Pattern
The Chain of Responsibility Pattern
The Interpreter Pattern

We're Finished

All 23 of the original GoF patterns are now covered. I'll put together a summary of all the patterns linking all the articles together soon.
Tags:

Comments

Ali Syed replied on Wed, 2010/06/16 - 8:06am

Great Work James,

I almost go through all you Design Pattern articles & learned lot from them.I like them all. Very much usefull.

Please also try to cover other Design Patterns which are not listed in GOF.

Krishan Chauhan replied on Sun, 2014/05/04 - 7:13am


Good explanation James!

Please take a note of builder pattern definition in the article. It's incorrectly referring to Proxy Pattern.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.