Builder pattern
Template:Short description 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.Template:Sfn
Overview
The builder design pattern solves problems like:[1]
- 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. Typically, this is done with method chaining and a fluent API.
The builder design pattern describes how to solve such problems:
- Encapsulate creating and assembling the parts of a complex object in a separate
Builderobject. - A class delegates object creation to a
Builderobject 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
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.Template:Sfn
Advantages
Advantages of the builder pattern include:[2]
- 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
Disadvantages of the builder pattern include:
- A distinct concrete builder must be created for each type of product.[2]
- 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
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 (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
Builder: an abstract interface for creating objects (product).ConcreteBuilder: provides implementation forBuilder. Constructs and assembles parts to build the objects, as a factory.
Examples
C++
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.
<syntaxhighlight lang="cpp"> 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() {
// directly construct a unique_ptr, because the constructor of
// Computer is private; therefore make_unique() can't be used
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();
} </syntaxhighlight>
C#
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.
<syntaxhighlight lang="csharp"> 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();
}
} </syntaxhighlight>
Java
Java makes extensive usage of the builder pattern. For example, the Template:Javadoc:SE class, which is used to construct a Template:Javadoc:SE.[4]
<syntaxhighlight lang="java"> 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!" </syntaxhighlight>
Similarly, the class Template:Javadoc:SE has an internal Template:Javadoc:SE class, which is used to build through setter methods, avoiding the constructor or the of() factory methods.[5]
<syntaxhighlight lang="java"> 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()); </syntaxhighlight>
Java streams (in java.util.stream) have an internal Builder<T> interface used to create Template:Javadoc:SE objects.[6]
Additionally, classes like Template:Javadoc:SE and Template:Javadoc:SE all have nested Builder classes within.[7][8]
Rust
In Rust, the builder pattern allows for an API to have optional parameters, because Rust does not allow default parameters or function overloading.
<syntaxhighlight lang="rust">
- [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);
} </syntaxhighlight>
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
Notes
References
External links
Template:Design Patterns Patterns
Template:Auth
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ 2.0 2.1 {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}