Design Patterns
Builder
Adding each part takes O(1) time (a constant amount). Building n parts takes O(n) total — the time grows with the number of parts.
The idea, in plain English
A builder works like ordering a custom burger at a counter. You add a bun, add a patty, add cheese, then say 'build it.' You add pieces one step at a time, and only at the end do you get the finished thing. In code, a builder puts together a complex object piece by piece, instead of in one giant step.
How it works
- 1You create a builder object that starts empty.
- 2You call methods on it, one at a time, to add each part. Each one can hand back the builder, so you can chain the next step.
- 3You call a final 'build' method to get the finished object.
When you'd use it
Use this when an object has many optional parts, or needs to be assembled step by step — like a burger, a form, or a complex settings object. One giant constructor call would get messy.
Common beginner mistakes
- Always return `this` (or `self`) from each step, or you'll break the chain of calls.
- Don't call build() before you've added all the parts you actually need.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Burger: bun + patty + cheeseNot sure this is the right topic? See the learning paths → or where this leads →