Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes OO, Patterns, UML and Refactoring and the fly likes Builder Pattern Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Builder Pattern Question" Watch "Builder Pattern Question" New topic

Builder Pattern Question

Ranch Hand

Joined: Apr 26, 2005
Posts: 54

I have 2 questions about the Builder pattern:

1) the defintion of this pattern is "to separate the construction of a complex object from its representation so that the construction process can create different objects". What is meant by "representation" in the definition?

2) Whats the point of the director object? All it does is delegates into the builder abstraction. The client could just invoke the builder directly to create the object and then call its gettor to retrieve the constructed object? What am I missing here?


Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
Imagine you have a set of data in a table, you can "represent" that data in many different ways, like an Excel Grid or a Pie Chart.

Then, a Builder could be used to create different different representations of the same model. This representations do not necessarily have to be related (as in a class hierarchy).

For instance, with a binary tree saved in memory structure you could create a JMenu or an XML DOM structure.

Since this objects are complex (you usually do not create such a structure with a single line of code), it typically takes more than one step to build the final product.

Builders are usually used with Composite objects, which they parse, and little by little build another product.

This way, you could have a builder that parse your binary tree in memory and depending on the node it creates a JMenu, a JMenuItem or adds a JMenuItem to another previously created JMenuItem.

Another builder would follow the same process, but the final product could be DOM structure instead.

In the future you could create another builder that creates a JTree.

The point is that the construction process has to be the same although every builder builds different products

The role of the director is to feed the builder with the raw material. In this case the Director may hold the model or the data with which the builder will be fed and also, the director will control the construction process through the builder.

For instance, the Director may visit every node of the binary tree, and pass the node to the corresponding building method, for the builder to decide what to do with it. Hence, the Builder creates the product little by little, but the construction process is orchestrated by the director.

For instance you could have a director that builds the product with the elements ordered in alphabetical order, or other director that order the elements in reversed order.

In a article about non-software examples of Software Patterns they say you could conceive the Builder the same way the fast-food restaurants work. The final product (Hamburger) depends on the combo that you choose, but the construction process is the same or fairly similar.
[ May 03, 2006: Message edited by: Edwin Dalorzo ]
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
To reiterate with other words:

Building a complex object involves executing a number of actions in a specific sequence. You can split the definition of that process by granularity - the rough order of actions on the one side, how to exactly execute each single action on the other.

The Builder pattern does exactly that: the Director defines the sequence of actions, the Builder how each action is executed.

A client that "just invoked the Builder directly" would *be* the Director, by definition.

Does that help?

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ranch Hand

Joined: Apr 26, 2005
Posts: 54
Edwin & Ilja,

thanks for the explanation - you have helped clear it up. Unfortunately all the examples I came across on the net didnt show the critical steps you both outlined, being:
1) the Director may have some model to feed to the builder.
2) the Directory can invoke multiple method calls on the builder to construct the complex object.

To my way of thinking, if there arent multiple steps to be performed to construct the object, which translates into the Director making multiple calls on the builder, then either the abstract factory or factory method patterns are more suitable?

many thanks!

Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
The truth is, Susan, that I have never found a good example of the builder pattern in the net.

They all just lead to more confusion about the pattern itself. In most of the cases I ended up in the same point that you, that's to say: I should use another creational pattern.

I have to admit that I have never faced a good scenario for the Builder pattern. Altough I have faced the reality to create complex objects, I cannot come up with a case where I could have represented them in different ways using the same construction process.

I think that would be another interesting question. In what particular context have other people used the Builder pattern?

I guess this would make a nice context for a book, too.
Peer Reynders

Joined: Aug 19, 2005
Posts: 2921
In my opinion you will have difficulties separating the Factory Method, Abstract Factory, and Builder Pattern if you "keep your nose too close to the implementation" of the pattern. They each work best as an expression of an essential idea:

Factory Method: A(n interface) method that (A) uses polymorphism to hide the actual type of the object constructed/returned and (B) hides the construction decisions/process from the client object. The client is guaranteed that the object constructed/returned by a factory method will implement a specific interface but the client is completely unaware of the actual type/class of the returned object. The knowledge of which class of object is appropriate is encapsulated in the implementation of the factory method and in the simplest case is directly dependent on the class that implements the factory method.
(In some cases the decisions may also be based on the state of the environment (e.g. configuration) and/or any information that the client may provide during the invocation of the factory method.***)
Benefits: Ensures that the client object implements to an interface, not the class implementation(s) � it ultimately reduces coupling between the client and the created object(s).

Abstract Factory: An interface aggregating factory methods for an entire family of related/dependent/coupled objects. Again polymorphism is used to hide the concrete implementation � but this time it's not just a single class hierarchy but it's multiple hierarchies for a family of (i.e. related) classes. It's a "Factory Method Squared" � not only don't you know the exact class of the objects that are being created for you � you don't even know which class of concrete factory you are dealing with. In this case it's likely that an implementation of a factory method will only construct objects from one-and-the-same class; i.e. a particular factory method implementation for a particular concrete factory will always construct objects from the same class (of course, exposed only through the interface specified by the factory method). However you will often obtain an Abstract Factory reference to a concrete factory through a "Fowler-style Factory Method".
Benefits: Ensures that the client object (A) implements to the family of related interfaces, not their various class implementation(s) and (B) implements to the Abstract Factory, not the various concrete factories � it ultimately reduces coupling between the client and the concrete factories and reduces coupling between the client and the families of related/dependent/coupled classes.

Builder: Separate object creation from object definition for all but the simplest of objects! Divide the construction process into two distinct stages, i.e. : persistent representation =(Director)=> construction actions =(Builder)=> object representation. GOF highlights the case where you have one director and many concrete builders. Personally, I find the case where you have multiple directors more interesting � like one director that reads property files and another that reads XML files � you have multiple directors, but you can reuse (all) your Builder(s).
Benefits: Separation of creational concerns from the object's domain behavior and state (i.e. why it's an object in the first place) � separation of concerns, potentially allowing multiple persistent representations to be used as the basis for the construction of object (graphs) that are essentially similar but require slightly varying implementations.

(Any refinements and corrections to these ideas and their descriptions are welcome.)

(*** Strictly speaking GOF doesn't allow for this, mainly to force the "Replace Conditional with Polymorphism" refactoring. However Fowler uses the term "Factory Method" in "Replace Constructor with Factory Method" to refer to a method that simply "knows" which class (implementing the specified interface) needs to be instantiated - that "Factory Method" doesn't implement an interface method and it is static (i.e. it can't be an interface method).

Once you understand the nuances of those three patterns, the concise GOF descriptions become sufficient.
  • Factory Method � Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets you defer instantiation to subclasses.
  • Abstract Factory � Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  • Builder � Separate the construction of a complex object from its representation so that the same construction process can create different representations.

  • Ilja Preuss

    Joined: Jul 11, 2001
    Posts: 14112
    One place where we use the Builder pattern is in assembling toolbars. We have a ToolbarBuilder with add methods for buttons, actions, components etc. and, of course, a getToolbar method.

    Another interesting variant are the EqualsBuilder and HashCodeBuilder from Jakarta Commons Lang.
    John Waugh

    Joined: May 01, 2006
    Posts: 6
    Another simple example of the builder pattern could be - Suppose windows explorer like utility needs to be made.

    The explorer contains two primary part 1)Tree like directory structure - shown in left pane 2)List of folder/files in the right pane.

    Now File system can be loaded in one common data structure. Here Director will invoke Left pane Builder for making tree and Right pane Builder for generating the list.

    For any change in file, only Right pane Builder will be invoked by Director.

    While change in directory structure may require both pane need to rebuild
    I agree. Here's the link:
    subject: Builder Pattern Question
    Similar Threads
    Builder Vs Factory
    BUILDER Pattern
    Design Patterns Questions
    Examples for Builder and ProtoType
    Mock Exam question