Seperate the construction of complex object from its representation so that the same construction process can create different representations.
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 representaions for the object that’s constrcuted.
- Specifies an abstract interface for creating parts of a Product object.
- Constructs and assembles parts of the product by implementing the Builder interface.
- Defines and keep tracks of the representation it creates.
- Provides an interface for retrieving the Product.
- Construct an object using the Builder interface.
- represent the complex object under construction. ConcreteBuilder builds the product’s internal representation and defines the process by which it’s assembled.
- Include the classes that define the constituent parts, including inteface for assembling the parts into final result.
- The client creates the Director object and configure with the desired Builder object.
- Director notifies the builder whenever a part of the product should be built.
- Builder handle the request from director and adds part to the product.
- The client retrieves the product from the builder.
Here are key consequences of the Builder pattern:
- It lets you vary a product’s internal representation.
- It isolates code for constrcution and representation.
- It gives you finer control over the construction process.
Typically there’s an abtract Builder class that defines an operation for each component that a director may ask it to create. The operations do nothing by default. A concreteBuilder class overrides operations for components it’s interested in creating.
Here are other implementation issues to consider:
- Assembly and construction interface. Builders construct their products in step by step fashion.
- Why not abstract class for product?. In the common case, the products produced by the concrete builders differ so greatly in their representation that there is little to gain from giving different products a common parerent class.
- Empty methods as default in Builder.
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 in on families of product objects ( either simple or complex ). Builder returns the product as a final step, but as far as the Abstract Factory pattern concerned, the product gets returned immediatly.
A composite is what the builder often builds.