The Builder pattern is a creational design pattern that lets you construct complex objects step by step.
It allows you to produce different types and representations of an object using the same construction code.
Use it when :
- You need to have a construction process that allow for different representations of the constructed object.
- The algorithm behind the complex object creation is independant of the parts constituting the object.
Participants
- Builder : Specifies an abstract interface for creating parts of the Product object.
- ConcreteBuilder :
- Constructs the different parts of the Product by implementing the Builder interface.
- Provide an interface to retrieve the Product.
- Director : Uses/reuses ConcreteBuilder(s) to construct a Product variant from the same set of parts.
- Product : The complex object in construction.
All the client has to do is to associate a ConcreteBuilder object to the Director.
After that, the Director uses the ConcreteBuilder to build a Product.
NB : UML class and sequence diagram from here
Pros
- Isolates code for construction and representation - enforcing modularity.
- Gives better control over the construction process and the resulting object - The product is constructed step by step, under the Director's control.
- Allow for easy variations over Product's internal representation.
Cons
- The builder interface shall be general enough to allow the creation of Products for every type of ConcreteBuilder. That means that you can clearly define a common construction sequence for every products representation.
- The overall complexity of the code increases since the pattern requires creating multiple new classes.
NB : The methods of the Builder are empty by default (not pure virtual) - so that the ConcreteBuilder can override only the operations they are interested in.
