Andre has posted 4 posts at DZone. View Full User Profile

Intro to Design Patterns: Builder Pattern

04.15.2008
| 63900 views |
  • submit to reddit
Either because you're new to them, or as a refresher, here is the start of a series on the "Gang of Four" design patterns. Andre Mare, the author of the Java Design Concepts blog, is a J2EE Specialist and has more than seven years experience in development and design of enterprise systems. Here he starts a series of articles that aim to introduce you to the "Gang of Four" design patterns. -- Geertjan Wielenga, JavaLobby Zone Leader

 

Intent of the Pattern

The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. - Gof

Type

Object Creational

Solution

The Builder Pattern simplifies the construction of complex objects by only specifying the type and content that the object requires. The construction process of the complex object will therefore allow for different representations of the complex object to be created by the different builders. Each of the concrete builder objects will construct a different representation of the complex object.

The Builder Pattern consists of a Builder, ConcreteBuilder, Director and Product.

  • The Director object is responsible for the construction process of the complex object but delegates the actual creation and assembly to the Builder interface.
  • The Builder object specifies the interface for creating parts of the complex object.
  • The Product represents the complex object that is created by the ConcreteBuilder objects. The Product consists of multiple parts that are created separately by the ConcreteBuilder objects.
  • The ConcreteBuilder objects create and assemble the parts that make up the Product through the Builder interface.

A client object creates an instance of the Director object and passes it the appropriate Builder object. The Director object invokes the methods on the Builder object to create and initialize specific parts of the Product object. The Builder receives content from the Director object and adds these to the Product object. The Client object has a reference to the Builder object and retrieves the created Product object from it.

Structure

Design Pattern, Builder Pattern, GOF

The construction of the Complex object (Product) is hidden by the Builder objects from the Client and Director objects. To change the internal representation of the complex object, a new concrete builder object is defined and used by the client through the Director object. Unlike other creational patterns, the Builder Pattern creates the complex object is sections through the Director and Builder objects. The Builder object may need access to information that was used in previous construction steps. This means that even thought the parts of a Product object is created in individual sections; they may interact with other sections to create the complex product object.

The complex Product objects do not usually have a shared abstract parent object, as their representation differ and a shared parent class or interface might not be possible. As the client object specify the Builder object, it should have the knowledge how to handle the product object that is created by the Builder object.

Java Sample Code

The example for the Builder Pattern is a meal that can be purchased at many fast food franchises. The complex Product is a combo meal that consists of a burger, beverage and a side order. The Builder objects are the different assistants at the till that knows how to create the combo meal for the client. The Director object is the instructions the client gives the assistant on how the specific order should be created.

Example Combo Meal:

Download Combo Meal Example

ComboMealClient.java
The ComboMealClient class makes use of the ComboMealDirector and the ComboMeal1ConcreteBuilder class to create a complex object called ComboMealProduct.

Code:

ComboMeal1ConcreteBuilder concreteBuilder = new ComboMeal1ConcreteBuilder();
ComboMealDirector mealDirector = new ComboMealDirector(concreteBuilder);
ComboMealProduct comboMealProduct = null;

mealDirector.constructComboMeal(SuperSize.HUGE);
comboMealProduct = concreteBuilder.getComboMealProduct();

ComboMealDirector.java
The ComboMealDirector class invokes the appropriate methods on the ConcreteBuilder (ComboMeal1ConcreteBuilder) to create a complex product ComboMealProduct.

Code:

public void constructComboMeal(SuperSize _mealSize) {
comboMealBuilder.buildBurgerPart();
comboMealBuilder.buildSideOrderPart(_mealSize);
comboMealBuilder.buildBeveragePart(_mealSize);
} // method constructComboMeal

ComboMealProduct.java
The ComboMealProduct class is the complex object whose individual parts is created by the different Builder objects.

ComboMealBuilder.java
The ComboMealBuilder class contains the interface that is used by the ComboMealDirector to create the complex object.

ComboMeal1ConcreteBuilder.java
The ComboMeal1ConcreteBuilder class contains implementation that is used by the ComboMealDirector to create the complex object.

Class Diagram Example

Design Pattern, Builder Pattern, GOF
Sequence Diagram Builder Pattern - Sequence Diagram

Sequence Diagram by "Yanic Inghelbrecht" with Trace Modeler

References

  • Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
    Design Patterns: Elements of Reusable Object-Oriented Software. Addison
    Wesley, 1995
References
AttachmentSize
combo meal example.png21.64 KB
combo meal example.JPG46.57 KB
Published at DZone with permission of its author, Andre Mare. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Kevin Moseley replied on Tue, 2008/04/15 - 10:09am

I am new to design patterns but could this also be described as a factory pattern?

Andre Mare replied on Tue, 2008/04/15 - 11:20am

No they are not the same, The Factory Method is also a Creational Pattern, but is classified as a Class Creational pattern, where the Builder Pattern is an Object Creational pattern. The difference in classification is that "Class" Creational patterns deal with the relationships between the parent class and subclasses.Inheritance plays a big role in these patterns. Object Creational patterns deal with the relationship between objects and is usually created during runtime.

The Builder pattern is the creation of objects step by step. The Factory Method pattern defines an interface and let the subclasses decide which object to instantiate.

 I will give an example of the Factory Method pattern soon.

Walter Laan replied on Wed, 2008/04/16 - 4:19am

Why does every concrete builder have a getComboMealProduct() method? Shouldn't the director createXXX(..) just return the product? Also, it seems you need a ConcreteBuilder for every Product you want to make.

Isn't the director just a factory with the builder as a strategy?

ComboMeal1ConcreteBuilder builder = new ComboMeal1ConcreteBuilder();
builder.setSuperSize(SuperSize.HUGE);
ComboMealProduct meal = ComboMealDirector.createComboMeal(builder);

 

 

Ashkan Roshanayi replied on Tue, 2008/07/15 - 1:03am in response to: Walter Laan

+1 for Walter Laan ;) I think only the Director should speak to client.

Ralph Engelmann replied on Fri, 2009/01/02 - 7:40am in response to: Walter Laan

I believe that the Director should not call a createXXX() function, because the Director should not interact with the product in order to separate the Concrete Product and the process of creation (Director) as far as possible. This is separation is important if the different concrete products have no common superclass (or a superclass which is too common, like Object).

For example assume a Java Program which deal with lists of integral numbers (native arrays and Lists). Also assume that there is a common process to initialize this lists, for example all lists contains 100 elements, the first 10 elements are of value 1, the next 10 elements are of value 2 and so one. This is the process implemented by the director.
The builder interface needs only 2 methods, one to create an empty list with an specified amount of elements, and one other method to set element x to value y.
Now you can implement 2 different concrete builder, one which creates an ArrayList and one which creates an array (int[]).
But the client have to invoke the concrete builder getProduct methods because there return type is to uncommon for an shared superclass.

nilesh gule replied on Thu, 2012/08/02 - 11:16am

Here is an example of Builder pattern in C# using Bill as an example.

http://www.nileshgule.com/2012/08/builder-design-pattern.html 

Comment viewing options

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