Builder pattern

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

The builder pattern is an object creation software design pattern. Unlike the abstract factory pattern and the factory method pattern whose intention is to enable polymorphism, the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern[citation needed] that occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

The builder pattern has another benefit: It can be used for objects that contain flat data (HTML code, SQL query, X.509 certificate…), that is to say, data that can't be easily edited step by step and hence must be edited at once.[citation needed]

Builder often builds a Composite. Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed. Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components are built. Builders are good candidates for a fluent interface.[1][better source needed]

Overview[edit]

The Builder [2] design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

The Builder design pattern solves problems like: [3]

  • 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.
See also the UML class and sequence diagram below.

Definition[edit]

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

Advantages[5][edit]

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

Disadvantages[5][edit]

  • Requires creating a separate ConcreteBuilder for each different type of Product.
  • Requires the builder classes to be mutable.

Structure[edit]

UML class and sequence diagram[edit]

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

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

Pseudocode[edit]

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
carBuilder.setSeats(2)
carBuilder.setSportsCar()
carBuilder.setTripComputer()
carBuilder.unsetGPS()
car := carBuilder.getResult()

Of course one could dispense with Builder and just do this:

car = new Car();
car.seats = 2;
car.type = CarType.SportsCar;
car.setTripComputer();
car.unsetGPS();
car.isValid();

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.

Examples[edit]

C#[edit]

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

    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);

        director.Construct();
        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.

C++[edit]

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

	private:
		// 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){}

	public:
		// Product specific functionality
		void print();
		void doSomething();
		void doSomethingElse();
};


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

	public:
		// default values for variables
		static const constexpr int defaultI = 1;
		static const constexpr float defaultF = 3.1415f;
		static const 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( const int i ){ this->i = i; return *this; }
		Builder& setF( const float f ){ this->f = f; return *this; }
		Builder& setC( const char c ){ this->c = c; return *this; }

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

			return *this;
		}

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

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

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

	cout << "Product internals dump:" << endl;
	cout << "i: " << this->i << endl;
	cout << "f: " << this->f << endl;
	cout << "c: " << this->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;
	b.setProductP();
	Product p2 = b.build(); // get Product P object
	b.setC('!'); // customize Product P
	Product p3 = b.build();
	p2.print(); // test p2
	p3.print(); // test p3
}

Crystal[edit]

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

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

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
end

class CarBuilder < Builder
  private getter car : Car

  def initialize
    @car = Car.new
  end

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

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

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

  def get_result
    return @car
  end
end

class CarBuilderDirector
  def self.construct : Car
    builder = CarBuilder.new
    builder.set_wheels(8)
    builder.set_seats(4)
    builder.set_color("Red")
    builder.get_result
  end
end

car = CarBuilderDirector.construct
p car

F#[edit]

 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
 7 
 8 
 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)
18 
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
27 
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
38         
39     interface ICarBuilder with
40         member x.SetColour = x.SetColour
41         member x.SetWheels = x.SetWheels
42         member x.GetResult = x.GetResult
43 
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.[7] 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.

Java[edit]

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

    private 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;
    }

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

    /**
     * The builder abstraction.
     */
    static class CarBuilder {
        private Car car;
 
        public CarBuilder() {
            car = new Car();
        }
        public Car build() {
            return car;
        }
        public CarBuilder setColor(final String color) {
            car.setColor(color);
            return this;
        }
        public CarBuilder setWheels(final int wheels) {
            car.setWheels(wheels);
            return this;
        }
    }
}

public class CarBuildDirector {
    private Car.CarBuilder builder;

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

    public Car construct() {
        return builder.setWheels(4)
                      .setColor("Red")
                      .build();
    }

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

        final CarBuildDirector carBuildDirector = new CarBuildDirector(builder);

        System.out.println(carBuildDirector.construct());
    }
}

Scala[edit]

/**
 * 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
}

class CarBuilderImpl extends CarBuilder {
    private var wheels:Int = 0
    private var color:String = ""

    override def setWheels(wheels:Int) = {
        this.wheels = wheels
        this
    }

    override def setColor(color:String) = {
        this.color = color
        this
    }

    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)
        println(carBuildDirector.construct) 
    }
}

Python[edit]

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

    @abstractmethod
    def set_wheels(self, value):
        pass

    @abstractmethod
    def set_seats(self, value):
        pass

    @abstractmethod
    def set_color(self, value):
        pass

    @abstractmethod
    def get_result(self):
        pass


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

    def set_wheels(self, value):
        self.car.wheels = value

    def set_seats(self, value):
        self.car.seats = value

    def set_color(self, value):
        self.car.color = value

    def get_result(self):
        return self.car


class CarBuilderDirector(object):
    @staticmethod
    def construct():
        builder = CarBuilder()
        builder.set_wheels(8)
        builder.set_seats(4)
        builder.set_color("Red")
        return builder.get_result()


car = CarBuilderDirector.construct()
print(car)


See also[edit]

References[edit]

  1. ^ Nahavandipoor, Vandad. "Swift Weekly - Issue 05 - The Builder Pattern and Fluent Interface". Github.com. 
  2. ^ 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. 
  3. ^ "The Builder design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-13. 
  4. ^ Gang Of Four
  5. ^ a b "Index of /archive/2010/winter/51023-1/presentations" (PDF). www.classes.cs.uchicago.edu. Retrieved 2016-03-03. 
  6. ^ "The Builder design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12. 
  7. ^ "Designing with types: Single case union types | F# for fun and profit". fsharpforfunandprofit.com. Retrieved 2017-03-30. 

External links[edit]