CreationalTypeScriptverifiedVerified

Builder Pattern in TypeScript

Separates the construction of a complex object from its representation, allowing the same construction process to produce different results.

How to Implement the Builder Pattern in TypeScript

1Step 1: Define the product class

class House {
  walls = 0;
  doors = 0;
  windows = 0;
  hasGarage = false;
  hasPool = false;

  describe(): string {
    const features = [
      `${this.walls} walls`, `${this.doors} doors`, `${this.windows} windows`,
      this.hasGarage ? "garage" : null,
      this.hasPool ? "pool" : null,
    ].filter(Boolean);
    return `House with ${features.join(", ")}`;
  }
}

2Step 2: Create the Builder with a fluent API

class HouseBuilder {
  private house = new House();

  reset(): this { this.house = new House(); return this; }
  setWalls(n: number): this { this.house.walls = n; return this; }
  setDoors(n: number): this { this.house.doors = n; return this; }
  setWindows(n: number): this { this.house.windows = n; return this; }
  setGarage(v: boolean): this { this.house.hasGarage = v; return this; }
  setPool(v: boolean): this { this.house.hasPool = v; return this; }

  build(): House {
    const result = this.house;
    this.reset();
    return result;
  }
}

3Step 3: Add a Director for preset configurations

class Director {
  buildMinimal(b: HouseBuilder): House {
    return b.reset().setWalls(4).setDoors(1).setWindows(2).build();
  }

  buildLuxury(b: HouseBuilder): House {
    return b.reset().setWalls(8).setDoors(4).setWindows(12)
      .setGarage(true).setPool(true).build();
  }
}

4Step 4: Build houses with and without a director

const builder = new HouseBuilder();
const director = new Director();

console.log(director.buildMinimal(builder).describe());
console.log(director.buildLuxury(builder).describe());

// Or build manually
const custom = builder.setWalls(6).setDoors(2).setWindows(8).setPool(true).build();
console.log(custom.describe());

Builder Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Builder Pattern in the Real World

Consider ordering a custom sandwich at a deli. You tell the sandwich artist (builder) each step — bread type, protein, toppings, sauce — and they assemble it in the right order. You don’t need to know how to layer ingredients properly; you just specify what you want, and the builder hands you a finished sandwich.