Builder pattern
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 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.
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]
Overview
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:
- 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 complex object directly.
A class (the same construction process) can use 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. [3]
Advantages[4]
- Allows you to vary a product’s internal representation.
- Encapsulates code for construction and representation.
- Provides control over steps of construction process.
Disadvantages[4]
- Requires creating a separate ConcreteBuilder for each different type of Product.
- Requires the builder classes to be mutable.
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
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
C#
/// <summary>
/// Represents a product created by the builder
/// </summary>
public class Car
{
public string Colour { get; }
public int Wheels { get; }
public Car(string colour, int wheels)
{
Colour = colour;
Wheels = wheels;
}
}
/// <summary>
/// The builder abstraction
/// </summary>
public interface ICarBuilder
{
string Colour { get; set; }
int Wheels { get; set; }
Car GetResult();
}
/// <summary>
/// Concrete builder implementation
/// </summary>
public class CarBuilder : ICarBuilder
{
public string Colour { get; set; }
public int Wheels { get; set; }
public Car GetResult()
{
return new Car(Colour, Wheels);
}
}
/// <summary>
/// The director
/// </summary>
public class CarBuildDirector
{
public CarBuildDirector() {}
public Car ConstructRedCar()
{
CarBuilder builder = new CarBuilder();
builder.Colour = "Red";
builder.Wheels = 4;
return builder.GetResult();
}
}
The Director assembles a car instance in the example above, delegating the construction to a separate builder object.
C++
////// 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
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#
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[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.
Java
/**
* 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;
}
@Override
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 car;
public CarBuilderImpl() {
car = new Car();
}
@Override
public Car build() {
return car;
}
@Override
public CarBuilder setColor(final String color) {
car.setColor(color);
return this;
}
@Override
public CarBuilder setWheels(final int wheels) {
car.setWheels(wheels);
return this;
}
}
public class CarBuildDirector {
private CarBuilder builder;
public CarBuildDirector(final CarBuilder builder) {
this.builder = builder;
}
public Car construct() {
return builder.setWheels(4)
.setColor("Red")
.build();
}
public static void main(final String[] arguments) {
final CarBuilder builder = new CarBuilderImpl();
final CarBuildDirector carBuildDirector = new CarBuildDirector(builder);
System.out.println(carBuildDirector.construct());
}
}
Scala
/**
* 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
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
References
- ↑ Nahavandipoor, Vandad. "Swift Weekly - Issue 05 - The Builder Pattern and Fluent Interface". Github.com.
- ↑ 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.
- ↑ Gang Of Four
- 1 2 "Index of /archive/2010/winter/51023-1/presentations" (PDF). www.classes.cs.uchicago.edu. Retrieved 2016-03-03.
- ↑ "Designing with types: Single case union types | F# for fun and profit". fsharpforfunandprofit.com. Retrieved 2017-03-30.
External links
The Wikibook Computer Science Design Patterns has a page on the topic of: Builder implementations in various languages |
- The JavaWorld article Build user interfaces without getters and setters (Allen Holub) shows the complete Java source code for a Builder.
- Item 2: Consider a builder by Joshua Bloch