Builder pattern

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

The Builder 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.


The Builder design pattern is one of the twenty-three well-known GoF design patterns[1] that describe how to solve recurring design problems in object-oriented software.

The Builder design pattern solves problems like:[2]

  • 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 separate Builder 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.


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.[1]


Advantages of the Builder pattern include:[3]

  • Allows you to vary a product’s internal representation.
  • Encapsulates code for construction and representation.
  • Provides control over steps of construction process.


Disadvantages of the Builder pattern include:[3]

  • Requires creating a separate ConcreteBuilder for each different type of product.
  • Requires the builder classes to be mutable.
  • Data members of class aren't guaranteed to be initialized.
  • Dependency injection may be less supported.


UML class and sequence diagram[edit]

A sample UML class and sequence diagram for the Builder design pattern.[4]

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 (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.
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[edit]

Builder Structure
Abstract interface for creating objects (product).
Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.


We have a Car class. The problem is that a car has many options. The combination of each option would lead to a huge list of constructors for this class. So we will create a builder class, CarBuilder. We will send to the CarBuilder each car option step by step and then construct the final car with the right options:

class Car is
  Can have GPS, trip computer and various numbers of seats.
  Can be a city car, a sports car, or a cabriolet.

class CarBuilder is
  method getResult() is
      output:  a Car with the right options
    Construct and return the car.

  method setSeats(number) is
      input:  the number of seats the car may have.
    Tell the builder the number of seats.

  method setCityCar() is
    Make the builder remember that the car is a city car.

  method setCabriolet() is
    Make the builder remember that the car is a cabriolet.

  method setSportsCar() is
    Make the builder remember that the car is a sports car.

  method setTripComputer() is
    Make the builder remember that the car has a trip computer.

  method unsetTripComputer() is
    Make the builder remember that the car does not have a trip computer.

  method setGPS() is
    Make the builder remember that the car has a global positioning system.

  method unsetGPS() is
    Make the builder remember that the car does not have a global positioning system.

Construct a CarBuilder called carBuilder
car := carBuilder.getResult()

So this indicates that the Builder pattern is more than just a means to limit constructor proliferation. It removes what could be a complex building process from being the responsibility of the user of the object that is built. It also allows for inserting new implementations of how an object is built without disturbing the client code.



/// <summary>
/// Represents a product created by the builder
/// </summary>
public class Car
    public string Make { get; set; }
    public string Model { get; set; }
    public int NumDoors { get; set; }
    public string Colour { get; set; }

    public Car(string make, string model, string colour, int numDoors)
        Make = make;
        Model = model;
        Colour = colour;
        NumDoors = numDoors;

/// <summary>
/// The builder abstraction
/// </summary>
public interface ICarBuilder
    string Colour { get; set; }
    int NumDoors { get; set; }

    Car GetResult();

/// <summary>
/// Concrete builder implementation
/// </summary>
public class FerrariBuilder : ICarBuilder
    public string Colour { get; set; }
    public int NumDoors { get; set; }

    public Car GetResult()
        return NumDoors == 2 ? new Car("Ferrari", "488 Spider", Colour, NumDoors) : null;        

/// <summary>
/// The director
/// </summary>
public class SportsCarBuildDirector
    private ICarBuilder _builder;
    public SportsCarBuildDirector(ICarBuilder builder) 
        _builder = builder;

    public void Construct()
        _builder.Colour = "Red";
        _builder.NumDoors = 2;

public class Client
    public void DoSomethingWithCars()

        var builder = new FerrariBuilder();
        var director = new SportsCarBuildDirector(builder);

        Car myRaceCar = builder.GetResult();

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


////// Product declarations and inline impl. (possibly Product.h) //////
class Product{
		// use this class to construct Product.
		class Builder;

		// variables in need of initialization to make valid object
		const int i;
		const float f;
		const char c;

		// Only one simple constructor - rest is handled by Builder
		Product( const int i, const float f, const char c ) : i(i), f(f), c(c){}

		// Product specific functionality
		void print();
		void doSomething();
		void doSomethingElse();

class Product::Builder{
		// variables needed for construction of object of Product class
		int i;
		float f;
		char c;

		// default values for variables
		static constexpr int defaultI = 1;
		static constexpr float defaultF = 3.1415f;
		static constexpr char defaultC = 'a';

		// create Builder with default values assigned
		// (in C++11 they can be simply assigned above on declaration instead)
		Builder() : i( defaultI ), f( defaultF ), c( defaultC ){ }

		// sets custom values for Product creation
		// returns Builder for shorthand inline usage (same way as cout <<)
		Builder& setI( int i ){ this->i = i; return *this; }
		Builder& setF( float f ){ this->f = f; return *this; }
		Builder& setC( char c ){ this->c = c; return *this; }

		// prepare specific frequently desired Product
		// returns Builder for shorthand inline usage (same way as cout <<)
		Builder& setProductP(){
			i = 42;
			f = -1.0f/12.0f;
			c = '@';

			return *this;

		// produce desired Product
		Product build(){
			// Here, optionaly check variable consistency
			// and also if Product is buildable from given information

			return Product( i, f, c );
///// Product implementation (possibly Product.cpp) /////
#include <iostream>

void Product::print(){
	using namespace std;

	cout << "Product internals dump:" << endl;
	cout << "i: " << i << endl;
	cout << "f: " << f << endl;
	cout << "c: " << c << endl;

void Product::doSomething(){}
void Product::doSomethingElse(){}
//////////////////// Usage of Builder (replaces Director from diagram)
int main(){
	// simple usage
	Product p1 = Product::Builder().setI(2).setF(0.5f).setC('x').build();
	p1.print(); // test p1

	// advanced usage
	Product::Builder b;
	Product p2 =; // get Product P object
	b.setC('!'); // customize Product P
	Product p3 =;
	p2.print(); // test p2
	p3.print(); // test p3


struct Product {
    i: i32,
    f: f32,
    c: char,

trait ProductBuilder {
    fn i(&mut self, i: i32) -> &mut Self;
    fn f(&mut self, f: f32) -> &mut Self;
    fn c(&mut self, c: char) -> &mut Self;
    fn build(&self) -> Product;

struct Builder {
    i: i32,
    f: f32,
    c: char,

impl Product {
    fn print(&self) {
        println!("Product {{ i: {}, f: {}, c: {} }}", self.i, self.f, self.c);

impl Builder {
    fn new() -> Builder {
        Builder {
            i: 0,
            f: 0.0,
            c: '\0',

    fn set_c(&mut self, c: char) -> &mut Builder {
        self.c = c;

    fn set_i(&mut self, i: i32) -> &mut Builder {
        self.i = i;

    fn set_f(&mut self, f: f32) -> &mut Builder {
        self.f = f;

    fn build_product(&self) -> Product {
        Product {
            i: self.i,
            f: self.f,
            c: self.c,

impl ProductBuilder for Builder {
    fn i(&mut self, i: i32) -> &mut Self {

    fn f(&mut self, f: f32) -> &mut Self {

    fn c(&mut self, c: char) -> &mut Self {

    fn build(&self) -> Product {

fn main() {
    let mut builder = Builder::new();

    let p1 = builder.i(5).c('ó').f(3.1416).build();

    let p2 = builder.c('!').f(-1.232e5).build();


class Car
  property wheels : Int32
  property seats : Int32
  property color : String

  def initialize(@wheels = 4, @seats = 4, @color = "Black")

abstract class Builder
  abstract def set_wheels(number : Int32)
  abstract def set_seats(number : Int32)
  abstract def set_color(color : String)
  abstract def get_result

class CarBuilder < Builder
  private getter car : Car

  def initialize
    @car =

  def set_wheels(value : Int32)
    @car.wheels = value

  def set_seats(value : Int32)
    @car.seats = value

  def set_color(value : String)
    @car.color = value

  def get_result
    return @car

class CarBuilderDirector
  def self.construct : Car
    builder =

car = CarBuilderDirector.construct
p car


 1 /// <summary>
 2 /// Represents a product created by the builder
 3 /// </summary>
 4 type Car () = 
 5     member val Wheels = 0 with get,set
 6     member val Colour = null with get,set
 9 // F# can actually enforce non-null strings being passed
10 //this doesn't show the full blown pattern, it just makes passing a null string a difficult/obvious syntax
11 module SpecialStrings = 
12     type NonNullString = |NonNullString of string
13     // shadow the constructor
14     let NonNullString x = 
15         match x with
16         | null -> None
17         | x -> Some (NonNullString x)
19 /// <summary>
20 /// The builder abstraction
21 /// </summary>    
22 type ICarBuilder = 
23     abstract member SetColour: SpecialStrings.NonNullString -> unit
24     abstract member SetWheels: int -> unit
25     // return an option type, in case current values aren't valid to create a Car
26     abstract member GetResult: unit -> Car option
28 /// <summary>
29 /// Concrete builder implementation
30 /// </summary>
31 type CarBuilder () = 
32     let car = Car()
33     member x.SetColour (NonNullString colour) = 
34         car.Colour <- colour 
35     member x.SetWheels count = 
36         car.Wheels <- count
37     member x.GetResult() = if not <| isNull car.Colour then Some car else None
39     interface ICarBuilder with
40         member x.SetColour = x.SetColour
41         member x.SetWheels = x.SetWheels
42         member x.GetResult = x.GetResult
44 /// <summary>
45 /// The director
46 /// </summary>
47 type CarBuildDirector () = 
48     member x.Construct() = 
49         let builder = CarBuilder()
50         NonNullString "Red"
51         |> Option.get
52         |> builder.SetColour
53         builder.SetWheels 4
54         builder.GetResult()

In F# we can enforce that a function or method cannot be called with specific data.[5] The example shows a simple way to do it that doesn't fully block a caller from going around it. This way just makes it obvious when someone is doing so in a code base.


 * Represents the product created by the builder.
class Car {
    private int wheels;
    private String color;

    public Car() {

    public String getColor() {
        return color;

    public void setColor(final String color) {
        this.color = color;

    public int getWheels() {
        return wheels;

    public void setWheels(final int wheels) {
        this.wheels = wheels;

    public String toString() {
        return "Car [wheels = " + wheels + ", color = " + color + "]";

 * The builder abstraction.
interface CarBuilder {
    Car build();

    CarBuilder setColor(final String color);

    CarBuilder setWheels(final int wheels);

class CarBuilderImpl implements CarBuilder {
    private Car carTmp;

    public CarBuilderImpl() {
        carTmp = new Car();

    public Car build() {
        Car car = new Car();
        return car;

    public CarBuilder setColor(final String color) {
        return this;

    public CarBuilder setWheels(final int wheels) {
        return this;

public class CarBuildDirector {
    private CarBuilder builder;

    public CarBuildDirector(final CarBuilder builder) {
        this.builder = builder;

    public Car construct() {
        return builder.setWheels(4)

    public static void main(final String[] arguments) {
        final CarBuilder builder = new CarBuilderImpl();

        final CarBuildDirector carBuildDirector = new CarBuildDirector(builder);



 * Represents the product created by the builder.
case class Car(wheels: Int, color: String)

 * The builder abstraction.
trait CarBuilder {
    def setWheels(wheels: Int): CarBuilder
    def setColor(color: String): CarBuilder
    def build(): Car

case class CarBuilderImpl(wheels: Int = 0, color: String = "") extends CarBuilder {
    override def setWheels(wheels: Int) = copy(wheels = wheels)
    override def setColor(color: String) = copy(color = color)
    override def build() = Car(wheels, color)

class CarBuildDirector(private val builder: CarBuilder) {
    def construct = builder.setWheels(4).setColor("Red").build()

    def main(args: Array[String]): Unit = {
        val builder = new CarBuilderImpl
        val carBuildDirector = new CarBuildDirector(builder)


from __future__ import print_function
from abc import ABCMeta, abstractmethod

class Car(object):
    def __init__(self, wheels=4, seats=4, color="Black"):
        self.wheels = wheels
        self.seats = seats
        self.color = color

    def __str__(self):
        return "This is a {0} car with {1} wheels and {2} seats.".format(
            self.color, self.wheels, self.seats

class Builder:
    __metaclass__ = ABCMeta

    def set_wheels(self, value):

    def set_seats(self, value):

    def set_color(self, value):

    def get_result(self):

class CarBuilder(Builder):
    def __init__(self): = Car()

    def set_wheels(self, value): = value
        return self

    def set_seats(self, value): = value
        return self

    def set_color(self, value): = value
        return self

    def get_result(self):

class CarBuilderDirector(object):
    def construct():
        return CarBuilder()

car = CarBuilderDirector.construct()


package builder
// builder.go

type BuildProcess interface {
	SetWheels() BuildProcess
	SetSeats() BuildProcess
	SetStructure() BuildProcess
	GetVehicle() VehicleProduct

type VehicleProduct struct {
	Wheels    int
	Seats     int
	Structure string
package builder
// director.go

type ManufacturingDirector struct {
	builder BuildProcess

func (f *ManufacturingDirector) Construct() {

func (f *ManufacturingDirector) SetBuilder(b BuildProcess) {
	f.builder = b
package builder
// car.go

type CarBuilder struct {
	vehicleProduct VehicleProduct

func (c *CarBuilder) SetWheels() BuildProcess {
	c.vehicleProduct.Wheels = 4
	return c

func (c *CarBuilder) SetSeats() BuildProcess {
	c.vehicleProduct.Seats = 5
	return c

func (c *CarBuilder) SetStructure() BuildProcess {
	c.vehicleProduct.Structure = "Car"
	return c

func (c *CarBuilder) GetVehicle() VehicleProduct {
	return c.vehicleProduct
package builder
// bike.go

type BikeBuilder struct{
	vehicleProduct VehicleProduct

func (b *BikeBuilder) SetWheels() BuildProcess {
	b.vehicleProduct.Wheels = 2
	return b

func (b *BikeBuilder) SetSeats() BuildProcess {
	b.vehicleProduct.Seats = 2
	return b

func (b *BikeBuilder) SetStructure() BuildProcess {
	b.vehicleProduct.Structure = "MotorBike"
	return b

func (b *BikeBuilder) GetVehicle() VehicleProduct {
	return b.vehicleProduct

See also[edit]


  1. ^ a b Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 97ff. ISBN 0-201-63361-2.CS1 maint: Multiple names: authors list (link)
  2. ^ "The Builder design pattern - Problem, Solution, and Applicability". Retrieved 2017-08-13.
  3. ^ a b "Index of /archive/2010/winter/51023-1/presentations" (PDF). Retrieved 2016-03-03.
  4. ^ "The Builder design pattern - Structure and Collaboration". Retrieved 2017-08-12.
  5. ^ "Designing with types: Single case union types | F# for fun and profit". Retrieved 2017-03-30.

External links[edit]