The Builder design pattern falls into the Creational design pattern category. Like the Factory design pattern, it abstracts the instantiation process. The critical distinction between the Builder and Factory patterns is that Builder is used to separate the representation of data and the construction logic of complex objects.
We need to have a way to create objects that represent houses. We know that even though there are many different types of houses, they typically share common elements, e.g. doors, windows, roofs, etc.
How can we design an object that can serve as an object factory, but separate the creation of the object from the representation of the object? We use the Builder design pattern to solve this.
- The Builder design pattern is used when the creation of complex objects needs to be independent of its representation.
- The creation process must allow different representations or the object that is constructed
The considerations that lead one to use the Builder design pattern are as follows:
- Do your classes share common elements?
- Do you want or need to build objects in a step wise manner?
- Will you need to build different complex classes comprised of common elements?
The Builder design pattern solves these problems by enforcing levels of delegation, and does so by providing he notion of "Clients," "Directors," and "Builders".
- A Builder is a do-er. It understands how to build primitive and complex objects. Going back to the house example, the builder would be a carpenter. The carpenter understands what it means to build a door, a roof, etc.
- A Director is an overseer of a Builder. It instructs the builder to build by providing him blue prints. E.g. "Build 1-Floor Ranch by following these steps... build frame, build roof, ... etc"
- A "Client" is the consumer. It knows what it wants, doesn't care too much about the details, but knows what the end result should be. Going back to the house example, the client would be a consumer.
- UML Diagram
Positive:Negative implications:
- Data represenation and construction logic are separated
- Directors can instruct Builders to construct new complex objects out of primitive objects
- Tends to reduce the size of classes by factoring out methods that are responsible for constructing complex objects into a single class.
- Can be difficult to model correctly
Modified:
19-Apr-2004
William Cava