Kurs JavaScript i TypeScript · Moduł 5: Zaawansowany JavaScript

Wzorzec Builder w JavaScript

8 min czytania ·
W tej lekcji6

W Parku Jurajskim tworzenie nowego dinozaura to złożony proces. Dr. Henry Wu nie może po prostu wrzucić wszystkich parametrów do jednego konstruktora - sekwencja genetyczna, dieta, habitat, poziom zagrożenia, wymagania temperaturowe... To dziesiątki parametrów! Na szczęście istnieje wzorzec Builder - elegancki sposób na budowanie złożonych obiektów krok po kroku.

Problem: Zbyt wiele parametrów

Wyobraź sobie konstruktor dinozaura, który przyjmuje jedenaście argumentów w sztywnej kolejności i bez żadnych nazw:

// Konstruktor z wieloma parametrami - nieczytelne i podatne na błędy
const dino = new Dinosaur(
  "Rexy",          // name
  "Tyrannosaurus",  // species
  "carnivore",      // diet
  8,                // age
  12000,            // weight
  "Sector A",       // habitat
  10,               // dangerLevel
  true,             // isActive
  38,               // optimalTemp
  null,             // mate
  ["hunt", "roar"]  // abilities
);
// Który parametr jest który? Łatwo pomylić kolejność!

Argumenty rozpoznajemy wyłącznie po pozycji. Zamiana wieku z poziomem zagrożenia przejdzie bez błędu, bo oba są liczbami, a pomyłka wyjdzie na jaw dopiero na wybiegu. Samo true czy null w środku listy nic nie mówi osobie czytającej kod.

Wzorzec Builder - rozwiązanie

Builder pozwala budować obiekt krok po kroku, z czytelnym API opartym na łańcuchach wywołań (method chaining). Wymagane dane, czyli imię i gatunek, trafiają do konstruktora, a każdą opcjonalną cechę ustawia osobna metoda o jasnej nazwie:

class DinosaurBuilder {
  constructor(name, species) {
    // Wymagane parametry w konstruktorze
    this.dinosaur = {
      name,
      species,
      abilities: []
    };
  }

  // Każda metoda ustawia właściwość i zwraca this (builder)
  setDiet(diet) {
    this.dinosaur.diet = diet;
    return this; // Kluczowe! Zwraca builder, umożliwiając chaining
  }

  setAge(age) {
    this.dinosaur.age = age;
    return this;
  }

  setWeight(weight) {
    this.dinosaur.weight = weight;
    return this;
  }

  setHabitat(habitat) {
    this.dinosaur.habitat = habitat;
    return this;
  }

  setDangerLevel(level) {
    this.dinosaur.dangerLevel = level;
    return this;
  }

  setActive(isActive) {
    this.dinosaur.isActive = isActive;
    return this;
  }

  setOptimalTemperature(temp) {
    this.dinosaur.optimalTemp = temp;
    return this;
  }

  addAbility(ability) {
    this.dinosaur.abilities.push(ability);
    return this;
  }

  // Metoda build() tworzy finalny obiekt
  build() {
    // Walidacja przed budowaniem
    if (!this.dinosaur.diet) {
      throw new Error("Dieta jest wymagana!");
    }
    return { ...this.dinosaur };
  }
}

Sercem wzorca jest linia return this: każda metoda zmienia jedną właściwość i oddaje ten sam builder, więc na wyniku można od razu wywołać kolejną metodę. Metoda build() kończy budowę - najpierw sprawdza dane, potem zwraca kopię zebranych właściwości.

Tak wygląda użycie. Każde ogniwo łańcucha mówi, co ustawia, więc kod czyta się jak protokół laboratoryjny:

// Użycie - czytelne i samodokumentujące się
const rexy = new DinosaurBuilder("Rexy", "Tyrannosaurus")
  .setDiet("carnivore")
  .setAge(8)
  .setWeight(12000)
  .setHabitat("Sector A")
  .setDangerLevel(10)
  .setActive(true)
  .setOptimalTemperature(38)
  .addAbility("hunt")
  .addAbility("roar")
  .build();

console.log(rexy);
// { name: "Rexy", species: "Tyrannosaurus", abilities: ["hunt", "roar"],
//   diet: "carnivore", age: 8, weight: 12000, habitat: "Sector A",
//   dangerLevel: 10, isActive: true, optimalTemp: 38 }

Na początku zawsze stoi new DinosaurBuilder(...), potem metody ustawiające w dowolnej kolejności, a build() na samym końcu, bo zwraca gotowy obiekt, a nie builder. Uwaga: spread w build() robi płytką kopię, więc tablica abilities jest wspólna dla buildera i gotowego dinozaura.

Fluent API - method chaining w praktyce

Kluczem do wzorca Builder jest Fluent API - każda metoda zwraca this, co pozwala łączyć wywołania w łańcuch. Ten sam trik świetnie sprawdza się przy zapytaniach do bazy dinozaurów. Najpierw sam builder zapytań:

// Fluent API do budowania zapytań o dinozaury
class DinoQueryBuilder {
  constructor() {
    this.query = {
      filters: {},
      sort: null,
      limit: 100,
      offset: 0
    };
  }

  whereSpecies(species) {
    this.query.filters.species = species;
    return this;
  }

  whereDiet(diet) {
    this.query.filters.diet = diet;
    return this;
  }

  whereDangerAbove(level) {
    this.query.filters.minDanger = level;
    return this;
  }

  whereActive(isActive = true) {
    this.query.filters.isActive = isActive;
    return this;
  }

  sortBy(field, direction = "asc") {
    this.query.sort = { field, direction };
    return this;
  }

  limitTo(count) {
    this.query.limit = count;
    return this;
  }

  skip(count) {
    this.query.offset = count;
    return this;
  }

  build() {
    return { ...this.query };
  }

  // Symulacja wykonania zapytania
  execute(database) {
    const query = this.build();
    console.log("Wykonuję zapytanie:", JSON.stringify(query, null, 2));

    let results = [...database];

    // Filtrowanie
    if (query.filters.species) {
      results = results.filter(d => d.species === query.filters.species);
    }
    if (query.filters.diet) {
      results = results.filter(d => d.diet === query.filters.diet);
    }
    if (query.filters.minDanger) {
      results = results.filter(d => d.dangerLevel >= query.filters.minDanger);
    }
    if (query.filters.isActive !== undefined) {
      results = results.filter(d => d.isActive === query.filters.isActive);
    }

    // Sortowanie
    if (query.sort) {
      results.sort((a, b) => {
        const dir = query.sort.direction === "asc" ? 1 : -1;
        if (a[query.sort.field] === b[query.sort.field]) return 0; // równe wartości
        return a[query.sort.field] > b[query.sort.field] ? dir : -dir;
      });
    }

    // Paginacja
    results = results.slice(query.offset, query.offset + query.limit);

    return results;
  }
}

Metody where... tylko zapisują filtry w obiekcie query - nic nie jest jeszcze filtrowane. Dopiero execute() przepuszcza kopię bazy przez filter(), sortuje ją i przycina przez slice(), a oryginalna tablica zostaje nietknięta. Funkcja porównująca zwraca 0 dla równych wartości, bo sort() wymaga spójnego porównania.

Teraz przykładowa baza i zapytanie złożone z pięciu czytelnych kroków:

// Przykładowa baza danych
const dinoDatabase = [
  { name: "Rexy", species: "Tyrannosaurus", diet: "carnivore", dangerLevel: 10, isActive: true },
  { name: "Blue", species: "Velociraptor", diet: "carnivore", dangerLevel: 8, isActive: true },
  { name: "Spike", species: "Triceratops", diet: "herbivore", dangerLevel: 4, isActive: true },
  { name: "Echo", species: "Velociraptor", diet: "carnivore", dangerLevel: 7, isActive: false },
  { name: "Trike", species: "Triceratops", diet: "herbivore", dangerLevel: 3, isActive: true }
];

// Budowanie zapytania z fluent API
const dangerousCarnivores = new DinoQueryBuilder()
  .whereDiet("carnivore")
  .whereDangerAbove(7)
  .whereActive()
  .sortBy("dangerLevel", "desc")
  .limitTo(5)
  .execute(dinoDatabase);

console.log("Niebezpieczne mięsożerne:", dangerousCarnivores);
// [{ name: "Rexy", ... }, { name: "Blue", ... }]

Z pięciu dinozaurów zostają Rexy i Blue: roślinożercy odpadają na filtrze diety, a Echo na filtrze aktywności. Ten sam styl spotkasz w wielu bibliotekach budujących zapytania do baz danych.

Builder z walidacją i wartościami domyślnymi

Builder może też pilnować zasad bezpieczeństwa parku. Konstruktor ustawia rozsądne wartości domyślne, a metody sprawdzają dane i zapisują błędy, zamiast przerywać budowę w połowie:

class EnclosureBuilder {
  constructor(name) {
    this.enclosure = {
      name,
      type: "standard",
      fenceVoltage: 10000,
      size: 1000,
      features: [],
      maxCapacity: 5,
      currentDinosaurs: []
    };
    this.errors = [];
  }

  setType(type) {
    const validTypes = ["standard", "aquatic", "aviary", "high-security"];
    if (!validTypes.includes(type)) {
      this.errors.push(`Nieprawidłowy typ wybiegu: ${type}`);
    }
    this.enclosure.type = type;
    return this;
  }

  setFenceVoltage(voltage) {
    if (voltage < 5000) {
      this.errors.push("Napięcie ogrodzenia musi być >= 5000V");
    }
    this.enclosure.fenceVoltage = voltage;
    return this;
  }

  setSize(squareMeters) {
    if (squareMeters < 100) {
      this.errors.push("Minimalna powierzchnia to 100 m²");
    }
    this.enclosure.size = squareMeters;
    return this;
  }

  setMaxCapacity(capacity) {
    this.enclosure.maxCapacity = capacity;
    return this;
  }

  addFeature(feature) {
    this.enclosure.features.push(feature);
    return this;
  }

  addDinosaur(dinosaur) {
    if (this.enclosure.currentDinosaurs.length >= this.enclosure.maxCapacity) {
      this.errors.push(`Wybieg pełny! Maks: ${this.enclosure.maxCapacity}`);
    }
    this.enclosure.currentDinosaurs.push(dinosaur);
    return this;
  }

  build() {
    if (this.errors.length > 0) {
      throw new Error(
        `Błędy budowania wybiegu:\n${this.errors.join("\n")}`
      );
    }
    return Object.freeze({ ...this.enclosure }); // Zamrożony obiekt
  }
}

Błędy zbierają się w tablicy errors, więc build() zgłasza wszystkie problemy naraz, a nie tylko pierwszy. Object.freeze() zamraża gotowy wybieg, ale tylko na pierwszym poziomie - do tablicy features wciąż da się coś dopisać.

Budowa wybiegu dla raptorów przechodzi walidację, bo napięcie, powierzchnia i liczba mieszkańców mieszczą się w limitach:

// Budowanie wybiegu
const raptorPaddock = new EnclosureBuilder("Raptor Paddock")
  .setType("high-security")
  .setFenceVoltage(25000)
  .setSize(5000)
  .setMaxCapacity(4)
  .addFeature("electrified-fence")
  .addFeature("motion-sensors")
  .addFeature("reinforced-gates")
  .addDinosaur("Blue")
  .addDinosaur("Charlie")
  .addDinosaur("Delta")
  .build();

console.log(raptorPaddock);
// { name: "Raptor Paddock", type: "high-security", fenceVoltage: 25000,
//   size: 5000, features: [...], maxCapacity: 4, currentDinosaurs: [...] }

Gdyby ktoś ustawił napięcie 3000 V, build() rzuciłby wyjątek z listą błędów i żaden wybieg by nie powstał. Pola, których nie ustawisz, zachowają wartości domyślne z konstruktora.

Builder z funkcjami (bez klas)

Builder nie wymaga klas - możemy użyć prostych funkcji. Stan raportu żyje w domknięciu, a metody zwracają obiekt builder zamiast this:

function createDinoReport(name) {
  const report = { name, sections: [] };

  const builder = {
    addVitals(heartRate, temperature) {
      report.sections.push({
        type: "vitals",
        heartRate,
        temperature
      });
      return builder;
    },

    addBehavior(description, threatLevel) {
      report.sections.push({
        type: "behavior",
        description,
        threatLevel
      });
      return builder;
    },

    addNote(text) {
      report.sections.push({
        type: "note",
        text,
        timestamp: new Date().toISOString()
      });
      return builder;
    },

    build() {
      return {
        ...report,
        generatedAt: new Date().toISOString(),
        totalSections: report.sections.length
      };
    }
  };

  return builder;
}

Zmienna report jest niedostępna z zewnątrz, więc zmienisz ją wyłącznie metodami buildera. Zwracanie builder zamiast this sprawia, że metoda zadziała nawet wtedy, gdy ktoś wyjmie ją z obiektu i wywoła osobno.

Raport weterynaryjny składamy z pięciu wpisów i jednego wywołania build():

// Budowanie raportu
const report = createDinoReport("Rexy")
  .addVitals(65, 38.2)
  .addBehavior("Spokojny, je regularnie", "low")
  .addNote("Zaobserwowano nowy wzorzec polowania")
  .addVitals(120, 39.1)
  .addBehavior("Pobudzony po burzy", "medium")
  .build();

console.log(JSON.stringify(report, null, 2));

Metoda build() dokłada datę wygenerowania i liczbę sekcji, tutaj 5, a JSON.stringify(report, null, 2) drukuje wynik z wcięciami.

Podsumowanie

Dr. Wu podsumowuje: "Wzorzec Builder to jak protokół tworzenia dinozaura - krok po kroku, z walidacją na każdym etapie:"

  1. Builder - buduje złożone obiekty krok po kroku zamiast jednego ogromnego konstruktora
  2. Fluent API / Method chaining - każda metoda zwraca this, umożliwiając łańcuchowe wywołania
  3. Walidacja - build() sprawdza poprawność przed utworzeniem obiektu
  4. Czytelność - kod jest samodokumentujący się, każdy parametr ma nazwaną metodę

Wzorzec Builder jest szczególnie przydatny, gdy:

  • Obiekt ma wiele opcjonalnych parametrów
  • Chcesz walidować dane przed utworzeniem obiektu
  • Budujesz zapytania, konfiguracje lub skomplikowane struktury danych

Moja rada: po wzorzec Builder sięgaj przy wielu opcjonalnych polach. Przy dwóch czy trzech wystarczy konstruktor przyjmujący jeden obiekt opcji, na przykład new Dinosaur({ name, diet }), bo nazwy pól same dokumentują kod. W następnej lekcji stworzysz własne klasy błędów, dzięki którym build() zgłosi problem precyzyjniej niż zwykłym Error. W laboratorium poniżej zbudujesz ReportBuilder oparty na łańcuchu metod.

Pamiętaj: Builder to protokół wylęgarni - dinozaur powstaje krok po kroku i wychodzi na świat dopiero po kontroli w build().

Kod do tej lekcji: index.js
// Wzorzec Builder w JavaScript
// Park Jurajski - Tworzenie zlozonych obiektow

console.log("=== WZORZEC BUILDER ===");

// Builder dla dinozaurow
class DinosaurBuilder {
  constructor(name, species) {
    this.dinosaur = { name, species, abilities: [] };
  }

  setDiet(diet) {
    this.dinosaur.diet = diet;
    return this; // Zwraca this - umozliwia chaining
  }

  setAge(age) {
    this.dinosaur.age = age;
    return this;
  }

  setWeight(weight) {
    this.dinosaur.weight = weight;
    return this;
  }

  setHabitat(habitat) {
    this.dinosaur.habitat = habitat;
    return this;
  }

  setDangerLevel(level) {
    this.dinosaur.dangerLevel = level;
    return this;
  }

  addAbility(ability) {
    this.dinosaur.abilities.push(ability);
    return this;
  }

  build() {
    if (!this.dinosaur.diet) {
      throw new Error("Dieta jest wymagana!");
    }
    return { ...this.dinosaur };
  }
}

// Tworzenie dinozaura z method chaining
const rexy = new DinosaurBuilder("Rexy", "Tyrannosaurus")
  .setDiet("carnivore")
  .setAge(8)
  .setWeight(12000)
  .setHabitat("Sector A")
  .setDangerLevel(10)
  .addAbility("hunt")
  .addAbility("roar")
  .build();

console.log("Rexy:", rexy);

const blue = new DinosaurBuilder("Blue", "Velociraptor")
  .setDiet("carnivore")
  .setAge(4)
  .setWeight(80)
  .setDangerLevel(8)
  .addAbility("hunt")
  .addAbility("communicate")
  .addAbility("coordinate-pack")
  .build();

console.log("Blue:", blue);

// === FLUENT QUERY BUILDER ===
console.log("\n=== QUERY BUILDER ===");

class DinoQueryBuilder {
  constructor() {
    this.query = { filters: {}, sort: null, limit: 100 };
  }

  whereDiet(diet) {
    this.query.filters.diet = diet;
    return this;
  }

  whereDangerAbove(level) {
    this.query.filters.minDanger = level;
    return this;
  }

  sortBy(field, direction = "asc") {
    this.query.sort = { field, direction };
    return this;
  }

  limitTo(count) {
    this.query.limit = count;
    return this;
  }

  execute(database) {
    let results = [...database];
    const f = this.query.filters;
    if (f.diet) results = results.filter(d => d.diet === f.diet);
    if (f.minDanger) results = results.filter(d => d.dangerLevel >= f.minDanger);
    if (this.query.sort) {
      const dir = this.query.sort.direction === "asc" ? 1 : -1;
      results.sort((a, b) =>
        a[this.query.sort.field] > b[this.query.sort.field] ? dir : -dir
      );
    }
    return results.slice(0, this.query.limit);
  }
}

const db = [
  { name: "Rexy", diet: "carnivore", dangerLevel: 10 },
  { name: "Blue", diet: "carnivore", dangerLevel: 8 },
  { name: "Spike", diet: "herbivore", dangerLevel: 4 },
  { name: "Echo", diet: "carnivore", dangerLevel: 7 },
  { name: "Trike", diet: "herbivore", dangerLevel: 3 },
];

const dangerous = new DinoQueryBuilder()
  .whereDiet("carnivore")
  .whereDangerAbove(7)
  .sortBy("dangerLevel", "desc")
  .limitTo(5)
  .execute(db);

console.log("Niebezpieczne miesozerne:", dangerous);

// === BUILDER Z WALIDACJA ===
console.log("\n=== BUILDER Z WALIDACJA ===");

class EnclosureBuilder {
  constructor(name) {
    this.enclosure = { name, type: "standard", features: [], dinosaurs: [] };
    this.errors = [];
  }

  setType(type) {
    const valid = ["standard", "aquatic", "aviary", "high-security"];
    if (!valid.includes(type)) this.errors.push("Nieprawidlowy typ: " + type);
    this.enclosure.type = type;
    return this;
  }

  addFeature(feature) {
    this.enclosure.features.push(feature);
    return this;
  }

  addDinosaur(name) {
    this.enclosure.dinosaurs.push(name);
    return this;
  }

  build() {
    if (this.errors.length > 0) {
      throw new Error("Bledy: " + this.errors.join(", "));
    }
    return Object.freeze({ ...this.enclosure });
  }
}

const paddock = new EnclosureBuilder("Raptor Paddock")
  .setType("high-security")
  .addFeature("electrified-fence")
  .addFeature("motion-sensors")
  .addDinosaur("Blue")
  .addDinosaur("Charlie")
  .addDinosaur("Delta")
  .build();

console.log("Wybieg:", paddock);

// TODO: Stworz ReportBuilder z method chaining
// addVitals(), addBehavior(), addNote(), build()
console.log("\n=== Cwiczenie ===");
console.log("Stworz ReportBuilder - patrz TODO w kodzie");

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Zadania praktyczne w grze

  • Układanie w poziomie

    Ułóż elementy tworzenia obiektu wzorcem Builder:

  • Klikanie w kolejności

    Ułóż elementy metody Builder umożliwiającej chaining:

  1. Ułóż w kolejnościSkładnia method chaining w Builder
  2. Kliknij w kolejnościKluczowy element wzorca Builder

Przydatne artykuły