What It Is
The Builder pattern constructs a complex object step by step. Instead of one constructor with a long, confusing argument list, the builder offers small named steps — and a final build() that returns the finished object.
Each step returns the builder itself, so the calls chain into a readable sentence.
Example: Building a Pizza
Compare new PizzaBuilder("large").cheese().topping("mushrooms") with a constructor like new Pizza("large", true, ["mushrooms"]) — the builder says what every value means, and optional parts are simply skipped.
Steps that chain
Every step is named and optional: the small pizza skips them all and comes out with cheese: false and an empty topping list. No true, undefined, false argument soup.
Output: TypeScript file and captured output
interface Pizza {
size: string
cheese: boolean
toppings: string[]
}
class PizzaBuilder {
private pizza: Pizza
constructor(size: string) {
this.pizza = { size: size, cheese: false, toppings: [] }
}
// Every step returns the builder itself, so calls chain.
cheese(): PizzaBuilder {
this.pizza.cheese = true
return this
}
topping(name: string): PizzaBuilder {
this.pizza.toppings.push(name)
return this
}
build(): Pizza {
return this.pizza
}
}
function describe(p: Pizza): string {
return `${p.size} pizza, cheese: ${p.cheese}, toppings: [${p.toppings.join(", ")}]`
}
const big = new PizzaBuilder("large")
.cheese()
.topping("mushrooms")
.topping("olives")
.build()
const small = new PizzaBuilder("small").build()
console.log(describe(big))
console.log(describe(small))
When to Use It
Use it when an object has many optional parts, or when construction has real steps that deserve names. Requests, queries, and configurations are classic builder territory.
Skip it for simple objects — an object literal with named properties, { size: "large", cheese: true, toppings: [] }, is already a fine little builder for the easy cases.
Pros and Cons
Pros: readable construction; optional parts without giant argument lists; the object can be validated once, in build().
Cons: a second class to write and maintain; overkill where an object literal already reads well.