Builder pattern


The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation. It is one of the Gang of Four design patterns.

Overview

The Builder design pattern is one of the GoF design patterns that describe how to solve recurring design problems in object-oriented software.
The Builder design pattern solves problems like:
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 the class.
The Builder design pattern describes how to solve such problems:
A class 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:
Disadvantages of the Builder pattern include:

UML class and sequence diagram

In the above UML class diagram,
the Director class doesn't create and assemble the ProductA1 and ProductB1 objects directly.
Instead, the Director refers to the Builder interface for building the parts of a complex object,
which makes the Director independent of which concrete classes are instantiated.
The Builder1 class implements the Builder interface by creating and assembling the ProductA1 and ProductB1 objects.


The UML sequence diagram shows the run-time interactions:
The 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
;ConcreteBuilder

Examples

C#">C Sharp (programming language)">C#


///
/// Represents a product created by the builder
///

public class Car
///
/// The builder abstraction
///

public interface ICarBuilder
///
/// Concrete builder implementation
///

public class FerrariBuilder : ICarBuilder
///
/// The director
///

public class SportsCarBuildDirector
public class Client

The Director assembles a car instance in the example above, delegating the construction to a separate builder object that has been given to the Director by the Client.