Builder Pattern
Separate a sequence of construction steps from the representation those steps produce.
· Last updated: 2026-11-07 · 10 min read
Overview
Whether a report comes out as plain text or HTML, the assembly sequence is the same: add the title first, then append each row. Duplicate that sequence inside every output formatter and you have to maintain the same choreography in multiple places, which is why you pull the construction order into one spot and let each step vary only the representation it builds.
One object drives the steps, requesting a title, then rows, while a second object translates each step into plain text, HTML, or another target format. That second object, assembling the product piece by piece, is a Builder.
UML
The UML diagram maps those two roles onto concrete types: ReportRecipe owns the step order and calls IReportBuilder, while TextBuilder and HtmlBuilder build their respective formats and hand the finished product back through Finish(). In the classic 1994 GoF structure, GetResult lives on each ConcreteBuilder because products need not share a type; here both builders produce a string, so Finish() sits right on the shared interface.
History
GoF cataloged Builder as a creational pattern in Design Patterns in 1994. Its focus is separating the construction of a complex object from its representation.1
GoF's motivating example in 1994 was an RTF document reader: a single RTFReader (Director) parsed tokens and forwarded step calls to an ASCIIConverter, TeXConverter, or TextWidgetConverter (ConcreteBuilder) to produce plain text, TeX markup, or a live UI widget tree from the same parse pass. In the 2008 second edition of *Effective Java* (Item 2), Joshua Bloch popularized a second idiom under the same name: a fluent inner Builder that replaces telescoping constructors when assembling an immutable object with many optional parameters.2
Why use it?
Copy-pasting the assembly flow across formats means any change to the recipe forces synchronized edits across every builder. Keeping the sequence inside ReportRecipe alone leaves each builder free to care only about formatting its own pieces.
Fluent method chaining (.WithTitle().WithRow()) is not what makes something a GoF Builder. Chaining is just call syntax. The pattern's real job is separating the construction sequence from the representation.
Example
Pass a title and a row through ReportRecipe, and out comes the plain-text report.
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(ReportRecipe.Build(new TextBuilder()));
// Declare common steps so each format does not repeat the construction recipe.
interface IReportBuilder
{
void Title(string title);
void Row(string value);
string Finish();
}
sealed class TextBuilder : IReportBuilder
{
private readonly List<string> parts = new();
public void Title(string title) => parts.Add(title);
public void Row(string value) => parts.Add("- " + value);
public string Finish() => string.Join("\n", parts);
}
sealed class HtmlBuilder : IReportBuilder
{
private readonly List<string> parts = new();
public void Title(string title) => parts.Add("<h1>" + System.Net.WebUtility.HtmlEncode(title) + "</h1>");
public void Row(string value) => parts.Add("<p>" + System.Net.WebUtility.HtmlEncode(value) + "</p>");
public string Finish() => string.Concat(parts);
}
// Own the sequence here and delegate the representation to the supplied builder.
static class ReportRecipe
{
public static string Build(IReportBuilder builder)
{
builder.Title("Report");
builder.Row("A < B");
return builder.Finish();
}
}
Report
- A < BBecause a builder accumulates in-progress parts in fields, you spin up a fresh builder per report; Finish() reads the assembled pieces without wiping that state.
An extended example
Run the same assembly procedure with HtmlBuilder. The HTML implementation encodes text so that a string from outside is not interpreted as a tag. The procedure stays; only the builder is swapped.
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(ReportRecipe.Build(new HtmlBuilder()));
// Declare common steps so each format does not repeat the construction recipe.
interface IReportBuilder
{
void Title(string title);
void Row(string value);
string Finish();
}
sealed class TextBuilder : IReportBuilder
{
private readonly List<string> parts = new();
public void Title(string title) => parts.Add(title);
public void Row(string value) => parts.Add("- " + value);
public string Finish() => string.Join("\n", parts);
}
sealed class HtmlBuilder : IReportBuilder
{
private readonly List<string> parts = new();
public void Title(string title) => parts.Add("<h1>" + System.Net.WebUtility.HtmlEncode(title) + "</h1>");
public void Row(string value) => parts.Add("<p>" + System.Net.WebUtility.HtmlEncode(value) + "</p>");
public string Finish() => string.Concat(parts);
}
// Own the sequence here and delegate the representation to the supplied builder.
static class ReportRecipe
{
public static string Build(IReportBuilder builder)
{
builder.Title("Report");
builder.Row("A < B");
return builder.Finish();
}
}
<h1>Report</h1><p>A < B</p>Plain text and HTML look nothing alike on screen, yet ReportRecipe drives both through the exact same sequence. That indirection pays off when multiple representations share a non-trivial assembly process; if you only have one simple product, a plain constructor or function is simpler.
TypeScript example
ReportRecipe owns the order of title and row steps; each builder turns those steps into text or HTML. Changing the recipe and changing a representation therefore affect different code.
// Declare common steps so each format does not repeat the construction recipe.
interface IReportBuilder {
title(value: string): void;
row(value: string): void;
finish(): string;
}
class TextBuilder implements IReportBuilder {
private readonly parts: string[] = [];
title(value: string): void { this.parts.push(value); }
row(value: string): void { this.parts.push("- " + value); }
finish(): string { return this.parts.join("\n"); }
}
function htmlText(value: string): string {
return value.replaceAll("&", "&").replaceAll("<", "<")
.replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
}
class HtmlBuilder implements IReportBuilder {
private readonly parts: string[] = [];
title(value: string): void { this.parts.push("<h1>" + htmlText(value) + "</h1>"); }
row(value: string): void { this.parts.push("<p>" + htmlText(value) + "</p>"); }
finish(): string { return this.parts.join(""); }
}
// Own the sequence here and delegate the representation to the supplied builder.
class ReportRecipe {
static build(builder: IReportBuilder): string {
builder.title("Report");
builder.row("A < B");
return builder.finish();
}
}
console.log(ReportRecipe.build(new TextBuilder()));
console.log(ReportRecipe.build(new HtmlBuilder()));Report
- A < B
<h1>Report</h1><p>A < B</p>The HTML builder encodes values inserted as text. Create a builder for each report; finish() reads its state without resetting it. The C# example follows the same two rules.
Declaring the result with Builder<T>
Switching the final product from a string to a string[] array should not force you to rewrite the assembly steps either. Parameterizing the interface as Builder<T> lets TextBuilder produce a single string and ArrayBuilder produce an array from the exact same director sequence.
Director plays the role ReportRecipe played earlier: it calls Begin(), feeds parts into AddPart(), and collects the finished product from Build(), which returns a defensive copy of the array so caller mutations never leak back into the builder.
C#
using System;
using System.Collections.Generic;
Console.WriteLine(Director.Build(new TextBuilder()));
Console.WriteLine(string.Join(",", Director.Build(new ArrayBuilder())));
// TYPES
interface IBuilder<T>
{
void Begin();
void AddPart(string part);
T Build();
}
static class Director
{
public static T Build<T>(IBuilder<T> builder)
{
builder.Begin(); builder.AddPart("header"); builder.AddPart("body");
return builder.Build();
}
}
abstract class Builder<T> : IBuilder<T>
{
protected readonly List<string> Parts = new();
public void Begin() => Parts.Clear();
public void AddPart(string part) => Parts.Add(part);
public abstract T Build();
}
sealed class TextBuilder : Builder<string>
{
public override string Build() => string.Join("|", Parts);
}
sealed class ArrayBuilder : Builder<string[]>
{
// Keep the mutable working list private to the builder.
public override string[] Build() => Parts.ToArray();
}header|body
header,bodyTypeScript
interface Builder<T> {
begin(): void;
addPart(part: string): void;
build(): T;
}
function buildWithDirector<T>(builder: Builder<T>): T {
builder.begin(); builder.addPart("header"); builder.addPart("body");
return builder.build();
}
class TextBuilder implements Builder<string> {
private parts: string[] = [];
begin(): void { this.parts = []; }
addPart(part: string): void { this.parts.push(part); }
build(): string { return this.parts.join("|"); }
}
class ArrayBuilder implements Builder<string[]> {
private parts: string[] = [];
begin(): void { this.parts = []; }
addPart(part: string): void { this.parts.push(part); }
// Separate the returned array from the next construction state.
build(): string[] { return [...this.parts]; }
}
console.log(buildWithDirector(new TextBuilder()));
console.log(buildWithDirector(new ArrayBuilder()).join(","));header|body
header,bodyAll Builder<T> locks down at compile time is the return type T. Fluent this-returning methods can make calls read nicely, yet T alone will not stop a caller from invoking AddPart() before Begin(); enforcing step order at compile time takes a separate technique such as staged interfaces (a step builder).
The official references describe the type-parameter syntax and library contracts.3
GoF polymorphic builders vs. fluent constructor builders
Before writing a builder, ask whether the problem calls for GoF's polymorphic Director–Builder split or Bloch's fluent parameter builder. When one multi-step construction sequence must target several distinct representations (plain text, HTML, PDF), separating the Director from a Builder interface pays off immediately. When there is only one target class and the goal is simply to avoid a seven-argument constructor, a standalone Director is dead weight.
Even for parameter assembly, modern languages often solve the problem at compile time without a builder class: C# provides named arguments, init-only and required properties, and record with-expressions, while TypeScript checks required fields directly on an options object. A naive mutable builder defers missing-field checks until Build() runs at runtime, trading away compile-time safety (see Algebraic data types and state modeling). Reserve dedicated builders for cases that genuinely accumulate variable-length parts or enforce cross-field invariants upon completion.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Creational patterns, Builder. ↩
- Joshua Bloch, Effective Java, 2nd ed., Addison-Wesley, 2008 (3rd ed. 2018), Item 2: "Consider a builder when faced with many constructor parameters." ↩
- C# generics; TypeScript generics ↩