The Participants

The Builder specifies an abstract interface for creating parts of a Product.

The ConcreteBuilder constructs and assembles parts of the product by implementing the Builder interface. It must also define and track the representation it creates.

The Product represents the object being constructed. It includes classes for defining the parts of the object, including any interfaces for assembling the parts into the final result.

The Director constructs an object using the Builder interface.

A Delicious Example

To demonstrate how the Builder design pattern works, we once again turn our hungry eyes to that most portable and simple of lunch foods: the humble sandwich.

Here's the thing about sandwiches: the only thing that defines a sandwich is something edible between two slices of bread. That's it. This means that a hot dog is a sandwich, which seems like a ridiculous statement but is technically correct (and technically correct is the best kind of correct).

That said, different types of sandwiches require different steps in order to make them, but they're still just sandwiches. Most of the time, the same kinds of ingredients will be used to create many different kinds of sandwiches. Let's see how we can use the Builder pattern to build us some of these yummy sandwiches.

To start off, we need tom implement the Director participant. We'll call our Director AssemblyLine, make it a class, and it will define in what steps the process of making a sandwich are called.

The nice thing about this pattern is that we can now reuse the AssemblyLine class on any SandwichBuilder we wish, and we have more fine-grained control over how the sandwiches are built.

(Yes, that pun was intentional. No, I'm not sorry.)

Will I Ever Use This Pattern?

Probably not. Let's face it, this is a lot of work to build these supposedly related items in a reusable manner. The patterns some degree of assumptions about how these objects should be created, and for me it's too many assumptions to rely on using this pattern in common projects. Seems to me like the Builder pattern has some uses, just not a lot of them.

Summary

The Builder pattern allows us to build related sets of objects with the same steps, but leaving the implementation of those steps up to the subclasses. It's not terribly useful as far as I can see, but if someone out there has a good use for it I'd love to hear about it in the comments.

As always, I like to provide code with my tutorials, so the repository for this pattern is over on GitHub and contains all of the sample code used here.