Skip to main content

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.

Prompt
Write a TypeScript program with a PizzaBuilder class: the constructor takes the size, the cheese and topping steps return the builder itself for chaining, and build returns the finished Pizza object (size, cheese flag, toppings array). Build one large pizza with cheese and two toppings and one plain small pizza, and print a one-line description of each.
Output: TypeScript file and captured output

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.