Design Pattern/Notes/Creational
Builder
Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.
Problem
Imagine a very complex object that requires lots of configuration parameters.
Potential Solutions:
- Many parameters could be optional. One simple solution is to make an abstract base class, and make many variants subclasses that extend the base class. The drawback is that there may be too many subclasses.
- A large constructor with many (optional) parameters. Resulting in very ugly code.
Solution
- Extract object construction code to separate objects called builders
- Execute a series of steps on a builder object to create an object, but not all steps need to be run.
- Some construction steps require different implementation, so you need to create several different builder classes that implement the same set of building steps.
- Optional: extract the series of calls to the builder steps to a Director class. Director defines the order of building steps execution. This can hide building details from client.
- Builder interface declares product construction steps that are common to all types of builders.
- Concrete Builders provide different implementations of the construction steps. Concrete builders may produce products that don’t follow the common interface.
- Products are resulting objects. Products constructed by different builders don’t have to belong to the same class hierarchy or interface.
- The Director class defines the order in which to call construction steps, so you can create and reuse specific configurations of products. See code
- The Client must associate one of the builder objects with the director.
Sample Code
Builders
Products
Components
Director
Client Demo
Limitation
Reference
How is this guide?