# Builder

> Construct complex objects step-by-step using method chaining — same construction process, different configurations, without constructor parameter hell.

- **Category**: Software Design
- **Subcategory**: creational
- **Canonical URL**: https://designpattern.fyi/patterns/builder/

---

## Description
**Intent**: Separate the construction of a complex object from its representation so the same process can produce different results.

**Context**: You need to build a complex object with many optional and required parameters — a query builder, HTTP request, report, or form config. Constructors with 10+ parameters are unreadable. Telescoping constructors (multiple overloads) don't scale. You want a fluent, readable construction API.

**Solution**: A Builder class exposes methods for each configurable part — `setSeats()`, `setEngine()`, `addGPS()`. Each method returns `this` for chaining. A final `build()` or `getProduct()` call assembles and returns the object. Optional: a Director class encapsulates common build sequences.


## Use Cases
Use when constructing complex objects with many optional parameters, multiple valid configurations, or step-by-step assembly — query builders, test fixture factories, HTML/XML builders.



## Implementation Example

```javascript
class CarBuilder {
  constructor() { this.reset(); }
  reset() { this.car = {}; }
  setSeats(number) { this.car.seats = number; return this; }
  setEngine(engine) { this.car.engine = engine; return this; }
  setGPS() { this.car.gps = true; return this; }
  getProduct() {
    const product = this.car;
    this.reset();
    return product;
  }
}

const builder = new CarBuilder();
const sportsCar = builder.setSeats(2).setEngine("V8").setGPS().getProduct();
console.log(sportsCar);

```



## Trade-offs


### Advantages

- Fluent method chaining is self-documenting — `builder.setEngine('V8').setSeats(2)` reads like config.

- Reuse the same builder for different configurations without duplicating construction logic.




### Considerations & Drawbacks

- More classes for what might be solved with a simple config object in straightforward cases.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/builder)

