Docs

Design Patterns — Fast Recall (Python)

Builder — assemble a complex object step by step


  • What: construct an object piece by piece, then `build()` the final result.
  • Why / when: many optional fields or a required order of steps → avoids the telescoping constructor (`__init__` with 10 args).
  • Signature move: each setter returns `self` so calls chain fluently.
  • Python truth: for pure data, keyword args / `@dataclass` usually replace Builder. Use it when construction has real logic or validation.
1class Burger: 2 def __init__(self): self.parts = [] 3 4class BurgerBuilder: 5 def __init__(self): self.b = Burger() 6 def add(self, x): 7 self.b.parts.append(x); return self # chainable 8 def build(self): return self.b 9 10burger = BurgerBuilder().add("patty").add("cheese").build() 11print(burger.parts) # ['patty', 'cheese']