Jump to content

Builder pattern

From Wikipedia, the free encyclopedia

The builder pattern is a design pattern that provides a flexible solution to various object creation problems in object-oriented programming. The builder pattern separates the construction of a complex object from its representation. It is one of the 23 classic design patterns described in the book Design Patterns and is sub-categorized as a creational pattern.[1]

Overview

[edit]

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.

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

Advantages

[edit]

Advantages of the builder pattern include:[3]

  • Allows for variation in a product's internal representation.
  • Encapsulates code for construction and representation.
  • Provides control over the steps of the construction process.

Disadvantages

[edit]

Disadvantages of the builder pattern include:

  • A distinct concrete builder must be created for each type of product.[3]
  • Builder classes must be mutable.
  • May hamper/complicate dependency injection.
  • In many null-safe languages, the builder pattern defers compile-time errors for unset fields to runtime.

Structure

[edit]

UML class and sequence diagram

[edit]
Image
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
Builder Structure
  • Builder: an abstract interface for creating objects (product).
  • ConcreteBuilder: provides implementation for Builder. Constructs and assembles parts to build the objects, as a factory.

Examples

[edit]

C++

[edit]

In this C++ example, the class Computer has an internal Builder class used to construct a Computer through a fluent API, while making the constructor private and having the build() method return a smart pointer to the Computer object.

import std;

using std::string;
using std::unique_ptr;

class Computer {
private:
    string cpu;
    string gpu;
    int ram; // default value
    int storage; // default value

    Computer(string cpu, string gpu, int ram, int storage):
        cpu{std::move(cpu)}, gpu{std::move(gpu)}, ram{ram}, storage{storage} {}
public:
    ~Computer() = default;

    void showSpecs() {
        std::println("Computer specs:");
        std::println("  CPU: {}", cpu);
        std::println("  GPU: {}", gpu);
        std::println("  RAM: {} GB", ram);
        std::println("  Storage: {} GB", storage);
    }

    class Builder {
    private:
        // Builder is given default parameters
        string cpu = "Generic CPU";
        string gpu = "Integrated Graphics";
        int ram = 16;
        int storage = 512;
    public:
        Builder() = default;

        Builder& ofCpu(string cpu) noexcept {
            this->cpu = std::move(cpu);
            return *this;
        }

        Builder& ofGpu(string gpu) noexcept {
            this->gpu = std::move(gpu);
            return *this;
        }

        Builder& withRam(int gb) noexcept {
            ram = gb;
            return *this;
        }

        Builder& withStorage(int gb) noexcept {
            storage = gb;
            return *this;
        }

        unique_ptr<Computer> build() {
            return unique_ptr<Computer>(new Computer(cpu, gpu, ram, storage));
        }
    };
};

int main() {
    unique_ptr<Computer> myComputer = Computer::Builder()
        .ofCpu("AMD Ryzen 7")
        .ofGpu("NVIDIA RTX 4070")
        .withRam(32)
        .withStorage(1000)
        .build();

    myComputer->showSpecs();
}

C#

[edit]

In this C# example, the Director assembles a Bicycle instance in the example above, delegating the construction to a separate builder object that has been given to the Director by the Client.

namespace Wikipedia.Examples;

public class Bicycle
{
    // Properties are made init-only or read-only for immutability
    public string Make { get; init; }
    public string Model { get; init; }
    public int Height { get; init; }
    public string Color { get; init; }

    public Bicycle(string make, string model, string color, int height)
    {
        Make = make;
        Model = model;
        Color = color;
        Height = height;
    }
}

/// <summary>
/// Correct Builder abstraction using standard fluent methods.
/// </summary>
public interface IBicycleBuilder
{
    IBicycleBuilder SetColour(string color);
    IBicycleBuilder SetHeight(int height);
    Bicycle Build();
}

/// <summary>
/// Concrete builder encapsulates its own state safely.
/// </summary>
public class GTBuilder : IBicycleBuilder
{
    private string _colour = "Black"; // Default value
    private int _height = 26; // Default value

    public IBicycleBuilder SetColor(string color)
    {
        _color = color;
        return this; // Returns itself for method chaining
    }

    public IBicycleBuilder SetHeight(int height)
    {
        _height = height;
        return this;
    }

    public Bicycle Build()
    {
        // Validation occurs here before instantiation if needed
        return new Bicycle("GT", "Avalanche", _color, _height);
    }
}

/// <summary>
/// Director controls the sequence using the builder's fluent interface.
/// </summary>
public class MountainBikeBuildDirector
{
    private readonly IBicycleBuilder _builder;

    public MountainBikeBuildDirector(IBicycleBuilder builder)
    {
        _builder = builder;
    }

    public Bicycle Construct()
    {
        // Director orchestrates the steps smoothly
        return _builder
            .SetColor("Red")
            .SetHeight(29)
            .Build();
    }
}

Java

[edit]

Java makes extensive usage of the builder pattern. For example, the java.lang.StringBuilder class, which is used to construct a java.lang.String.[5]

StringBuilder sb = new StringBuilder()
    .append("Hello")
    .append(", ")
    .append("world")
    .append("!")
    .insert(0, "[INFO] ");

String message = sb.toString();
System.out.println(message); // prints "[INFO] Hello, world!"

Similarly, the class java.util.Locale has an internal Builder class, which is used to build through setter methods, avoiding the constructor or the of() factory methods.[6]

import java.util.Locale;

Locale frenchCanadian = new Locale.Builder()
    .setLanguage("fr") // set language to French
    .setRegion("CA") // set region to Canada
    .setVariant("POLY") // sets a custom variant
    .build(); // construct the Locale

// prints "French (Canada,POLY)"
System.out.println(frenchCanadian.getDisplayName());
// prints "fr-CA-x-lvariant-POLY"
System.out.println(frenchCanadian.toLanguageTag());

Java streams (in java.util.stream) have an internal Builder<T> interface used to create java.util.stream.Stream<E> objects.[7]

Additionally, classes like java.net.http.HttpClient and java.net.http.HttpRequest all have nested Builder classes within.[8][9]

Rust

[edit]

In Rust, the builder pattern allows for an API to have optional parameters, because Rust does not allow default parameters or function overloading.

#[derive(Debug)]
pub struct Server {
    host: String,
    port: u16,
}

impl Server {
    pub fn builder() -> ServerBuilder {
        ServerBuilder::default()
    }
}

#[derive(Default)]
pub struct ServerBuilder {
    host: Option<String>,
    port: Option<u16>,
}

impl ServerBuilder {
    pub fn host(mut self, host: &str) -> Self {
        self.host = Some(host.to_string());
        self
    }

    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    pub fn build(self) -> Result<Server, &'static str> {
        let host = self.host.ok_or("Host is required")?;
        let port = self.port.unwrap_or(8080);

        Ok(Server { host, port })
    }
}

fn main() {
    let server = Server::builder()
        .host("127.0.0.1")
        .port(3000)
        .build();
        
    println!("{:?}", server);
}

While, unlike C++, Rust cannot allow a type to be nested inside another (like Server::Builder), instead Server may have a method builder() to create a ServerBuilder, whose build() method finally returns a Server instance.

See also

[edit]

Notes

[edit]
  1. 1 2 Gamma et al. 1994, p. 97.
  2. "The Builder design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-13.
  3. 1 2 "Index of /archive/2010/winter/51023-1/presentations" (PDF). www.classes.cs.uchicago.edu. Retrieved 2016-03-03.
  4. "The Builder design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.
  5. Oracle Corporation (7 July 2026). "Class StringBuilder". docs.oracle.com. Oracle Corporation.
  6. Oracle Corporation (7 July 2026). "Class Locale.Builder". docs.oracle.com. Oracle Corporation.
  7. Oracle Corporation (7 July 2026). "Interface Stream.Builder<T>". docs.oracle.com. Oracle Corporation.
  8. Oracle Corporation (7 July 2026). "Interface HttpClient.Builder". docs.oracle.com. Oracle Corporation.
  9. Oracle Corporation (7 July 2026). "Interface HttpRequest.Builder". docs.oracle.com. Oracle Corporation.

References

[edit]
[edit]