Builder
07 Mar 2022Intent
Separate the construction of a complex object from its representation so that the same construction process can create different representatives.
Applicability
Use the builder pattern when:
- The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.
- The construction process must allow different representations for the object that's constructed.
Structure
Participants
- Builder: specifies and abstract interface for creating parts of Product object.
- Concrete Builder: constructs and assembles parts of the product by implementing the Builder interface, Defines and keeps track of representation it creates, provides an interface for retrieving the product.
- Director: constructs an object using the Builder interface.
- Product: represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled, includes classes that define the constituent parts, including interfaces for assembling the parts into the final result.
Collaborations
- The client creates the Director object and configures it with the desired Builder object.
- Director notifies the builder whenever a part of the product should be built.
- Builder handles requests from the director and adds parts of the product.
- The client retrives the product from the builder.
Consequences
Key consequences of builder pattern:
- It lets you vary a product's internal representation.
- It isolates code for construction and representation.
- It gives you finer control over the construction process.
Implementation
- Assembly and construction interface.
- Why no abstract class for products?
- Empty methods as default in Builder.
Sample Code
Related Patterns
- Abstract Factory is similar to builder in that it too may construct complex objects. The primary difference is that the builder pattern focuses on constructing a complex object step by step. Abstract Factory's emphasis is on families of product objects. Builder returns the product as a final step, but in Abstract Factory, the product gets returned immediately.
- A Composite is what the builder often builds.