Overview
The Builder design pattern is one of the '' Design Patterns'' that describe how to solve recurring design problems in object-oriented software. The Builder design pattern solves problems like: * How can a class (the same construction process) create different representations of a complex object? * How can a class that includes creating a complex object be simplified? Creating and assembling the parts of a complex object directly within a class is inflexible. It commits the class to creating a particular representation of the complex object and makes it impossible to change the representation later independently from (without having to change) the class. The Builder design pattern describes how to solve such problems: * Encapsulate creating and assembling the parts of a complex object in a separateBuilder
object.
* A class delegates object creation to a Builder
object instead of creating the objects directly.
A class (the same construction process) can delegate to different Builder
objects to create different representations of a complex object.
Definition
The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations.Advantages
Advantages of the Builder pattern include: * Allows you to vary a product's internal representation. * Encapsulates code for construction and representation. * Provides control over steps of construction process.Disadvantages
Disadvantages of the Builder pattern include: * A distinct ConcreteBuilder must be created for each type of product. * Builder classes must be mutable. * May hamper/complicate dependency injection.Structure
UML class and sequence diagram
Director
class doesn't create and assemble the ProductA1
and ProductB1
objects directly.
Instead, the Director
refers to the Builder
interface for building (creating and assembling) the parts of a complex object,
which makes the Director
independent of which concrete classes are instantiated (which representation is created).
The Builder1
class implements the Builder
interface by creating and assembling the ProductA1
and ProductB1
objects.
Director
object calls buildPartA()
on the Builder1
object, which creates and assembles the ProductA1
object.
Thereafter,
the Director
calls buildPartB()
on Builder1
, which creates and assembles the ProductB1
object.
Class diagram
;Builder :Abstract interface for creating objects (product). ;ConcreteBuilder :Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.Examples
A C# example:See also
* Currying * FluentQueryBuilderReferences
External links
{{Design Patterns Patterns Software design patterns Articles with example Java code