Builder Pattern Tutorial with Java Examples
Learn the Builder Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
Join the DZone community and get the full member experience.
Join For FreeToday'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. Thedefinition of Builder provided in the original Gang of Four book on DesignPatterns 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 overall 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.
Enjoy the Whole "Design Patterns Uncovered" Series:
Creational Patterns
- Learn The Abstract Factory Pattern
- Learn The Builder Pattern
- Learn The Factory Method Pattern
- Learn The Prototype Pattern
Structural Patterns
- Learn The Adapter Pattern
- Learn The Bridge Pattern
- Learn The Decorator Pattern
- Learn The Facade Pattern
- Learn The Proxy Pattern
Behavioral Patterns
- Learn The Chain of Responsibility Pattern
- Learn The Command Pattern
- Learn The Interpreter Pattern
- Learn The Iterator Pattern
- Learn The Mediator Pattern
- Learn The Memento Pattern
- Learn The Observer Pattern
- Learn The State Pattern
- Learn The Strategy Pattern
- Learn The Template Method Pattern
- Learn The Visitor Pattern
Opinions expressed by DZone contributors are their own.
Comments