encyclopegia.org

Builder pattern

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.

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. ==Overview== 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. 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 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== 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. ==Structure== 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 build() { return unique_ptr (new Computer(cpu, gpu, ram, storage)); } }; }; int main() { unique_ptr myComputer = Computer::Builder() .ofCpu("AMD Ryzen 7") .ofGpu("NVIDIA RTX 4070") .withRam(32) .withStorage(1000) .build(); myComputer->showSpecs(); } 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; } } /// /// Correct Builder abstraction using standard fluent methods. /// public interface IBicycleBuilder { IBicycleBuilder SetColour(string color); IBicycleBuilder SetHeight(int height); Bicycle Build(); } /// /// Concrete builder encapsulates its own state safely. /// 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); } } /// /// Director controls the sequence using the builder's fluent interface. /// 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(); } } 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. 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 interface used to create java.util.stream.Stream objects. Additionally, classes like java.net.http.HttpClient and java.net.http.HttpRequest all have nested Builder classes within. [derive(Debug)] pub struct Server { host: String, port: u16, } impl Server { pub fn builder() -> ServerBuilder { ServerBuilder::default() } } [derive(Default)] pub struct ServerBuilder { host: Option , port: Option , } 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 { 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. ==Notes== ==References== ==External links==

References

No reference rows published for this article.

Cite this article

MLA

"Builder pattern." encyclopegia.org, 2026, https://encyclopegia.org/wiki/builder-pattern. Accessed 24 November 2026.

Chicago

"Builder pattern." encyclopegia.org. Accessed November 24, 2026. https://encyclopegia.org/wiki/builder-pattern.

APA

encyclopegia.org. (2026). Builder pattern. Retrieved November 24, 2026, from https://encyclopegia.org/wiki/builder-pattern

Accessed November 24, 2026 · CC BY-SA 4.0 · citation page · JSON

Related articles

Battle of Fleurus (1794)

enwiki · references available

Battle of Eylau

enwiki · references available

Mieczysław Karłowicz

enwiki · references available

Cut, copy, and paste

enwiki · references available

Battle of Sainte-Foy

enwiki · references available

Battle of Rocroi

enwiki · references available
CC BY-SA 4.0 · share-alike · https://en.wikipedia.org/w/index.php?oldid=1367071363 · 0.5 · snapshot enwiki-001367071363

Cite · JSON · Search

Related services and records

Services

  • Estate — measured countries, lanes and facts
  • Intel — live corroborated events
  • Legal — statutes, cases and citations
  • Encyclopedia — articles with inline sources
  • Space — launches, satellites and orbits
  • Search — federated search and reports
  • Pass — passport account and SSO
  • Corpora — read-only corpus origins
  • e01 — self-hosted corpora and tools

Text and metadata only; each target carries its own sources. Missing data is published as no-data, never estimated.