Builder 模式通过逐步构建复杂对象,将构建过程与表示分离。它特别适用于具有许多参数或可选部分的对象,能生成可读性强、灵活的对象构建方式,避免了笨拙的构造函数。
Builder 解决的问题
Objects with MANY parameters (especially optional ones) lead to problems:
✗ huge constructors: new Pizza('large', true, false, true, 'thin', false, ...) →
unreadable (which boolean is what?); hard to use; error-prone
✗ many constructor overloads (telescoping constructors) → messy
→ Builder provides a clean, readable, step-by-step way to construct such objects.
Builder 如何工作
pizza = ()
.()
.()
.()
.()
.();
