When Would You Use the Builder Pattern

When would you use the Builder Pattern?

The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within one method call.

One example of using a builder is a building an XML document, I've used this model when building HTML fragments for example I might have a Builder for building a specific type of table and it might have the following methods (parameters are not shown):

BuildOrderHeaderRow()
BuildLineItemSubHeaderRow()
BuildOrderRow()
BuildLineItemSubRow()

This builder would then spit out the HTML for me. This is much easier to read than walking through a large procedural method.

Check out Builder Pattern on Wikipedia.

Why do we need to use the builder design pattern when we can do the same thing with setters?

The builder pattern can be useful to:

  • apply some check on the data used to initialize the object. For example if you need a double check between variables
  • create immutable objects. You can't change an object once initialized, so you can't use setters
  • add readability of code.
  • reduce the code used to initialize the object
  • have the instance in a valid state. Using setters the object instance can be in a not valid state before all the setters are called.

Note on using the builder to create immutable objects.

When you work in a multithread environment an immutable object can be shared between threads without explicit synchronization. Because the object can't change during the time is not possible to have a race condition accessing and modifying it by two threads at the same time.

When should I use builder Design Pattern?

The Builder Design Pattern helps us to slice the operations of building an object. It focuses on constructing a complex object step by step. It also enforces a process to create an object as a finished product. That means an object has to be massaged by some instructed steps before it is ready and can be used by others.

Generally, It allows you to encapsulate the complex create logic.

Builder pattern is very much like factory pattern. The key difference between a builder and factory is that a builder is useful when you need to do lots of things to build an object.

For more information:

http://en.wikipedia.org/wiki/Builder_pattern

http://www.codeproject.com/KB/architecture/Builder_Design_Pattern.aspx

Difference between builder pattern and constructor

I agree with your view that a Builder is really just a glorified constructor, and that the "builder pattern is just a way to build an object similar to what a constructor does".

However, here are a few of scenarios where the complexity of constructing an object makes the use of a Builder compelling.

Object's dependencies collected over period of time

In Java, StringBuilder is commonly used when building a string over a period of time, or rather, within a complex procedure. For instance, if a server is communicating with a client over a socket, and wants to append some client responses to the string, but not others, and perhaps remove certain responses that were previously appended,the StringBuilder class can be used to do so. At the end of the client/server session, the server can invoke StringBuilder#toString to get the built String.

Lots of parameters

If a constructor has dozens of parameters, it may make the code more readable or easy to maintain to use a builder.

E.g.

new Foo(1,2,3,4,5,6,7,8,9,10,11,12)

Vs.

Foo.newBuilder()
.bar(1)
.bar(2)
.quux(3)
...
.build()

Constructing object graphs

Similar to the "lots of parameters" scenario, I think that the scenario where a builder is most compelling is when constructing a complex object graph. The other answers in this question refer to the telescoping anti-pattern. This scenario (building a complex object graph) can lead to "telescoping", which the Builder helps resolve.

For instance, imagine you have an object-oriented pipeline interface, where a Pipeline depends on Sequence which depends on Stage. A PipelineBuilder would not only provide a nice wrapper around the constructor of Pipeline, but also around the constructors Sequence and Stage, allowing you to compose a complex Pipeline from a single Builder interface.

Instead of telescoping constructors like so:

new Pipeline(
new Sequence(
new Stage(
new StageFunction() {
public function execute() {...}
}
),
new Stage(
new StageFunction() {
public function execute() {...}
}
)
)
)

A PipelineBuilder would allow you to "collapse" the telescope.

Pipeline.newBuilder()
.sequence()
.stage(new StageFunction () {
public function execute() {...}
})
.stage(new StageFunction () {
public function execute() {...}
})
.build()

(Even though I have used indentation in a way that is reflective of the telescoping constructors, this is merely cosmetic, as opposed to structural.)

What is the difference between Builder Design pattern and Factory Design pattern?

With design patterns, there usually is no "more advantageous" solution that works for all cases. It depends on what you need to implement.

From Wikipedia:

  • Builder focuses on constructing a
    complex object step by step. Abstract
    Factory emphasizes a family of product
    objects (either simple or complex).
    Builder returns the product as a final
    step, but as far as the Abstract
    Factory is concerned, the product gets
    returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more
    customizable, subclasses proliferate)
    and evolve toward Abstract Factory,
    Prototype, or Builder (more flexible,
    more complex) as the designer
    discovers where more flexibility is
    needed.
  • Sometimes creational patterns are complementary: Builder can use one
    of the other patterns to implement
    which components get built. Abstract
    Factory, Builder, and Prototype can
    use Singleton in their
    implementations.

Wikipedia entry for factory design pattern:
http://en.wikipedia.org/wiki/Factory_method_pattern

Wikipedia entry for builder design pattern:
http://en.wikipedia.org/wiki/Builder_pattern

What would be considered good examples of implementing the builder pattern when used in the development of a GUI?

Joshua Bloch's Item 2: Consider a builder is always a good place to start. Regarding GUI development, many layout managers use the builder pattern. A Visual Guide to Layout Managers is a good introduction.



Related Topics



Leave a reply



Submit