← Back to TypeScript Course | Chapter 16: Advanced Patterns | Lesson 1 of 7

Builder Pattern की जानकारी

Builder Pattern complex objects को step by step बनाता है बजाय एक बड़ी constructor call की ज़रूरत के। यह उपयोगी है जब किसी object में कई optional settings हों या construction पढ़ने में आसान होना चाहिए।
Syntax
typescript
class Builder {
  private product: Partial<Product> = {};
  setX(value: type): this {
    this.product.x = value;
    return this;
  }
  build(): Product {
    return this.product as Product;
  }
}

Basic Builder

एक basic builder एक class है जो एक final .build() method से पहले कई method calls में configuration accumulate करता है जो पूरी तरह से constructed object assemble और return करता है, एक हर option को एक साथ लेने वाली single बड़ी constructor के बजाय।

उदाहरण: Basic Builder

typescript
class PizzaBuilder {
  private toppings: string[] = [];
  addTopping(topping: string): this {
    this.toppings.push(topping);
    return this;
  }
  build(): string {
    return `Pizza with ${this.toppings.join(", ")}`;
  }
}
console.log(new PizzaBuilder().addTopping("cheese").build());

Fluent Methods

एक builder पर Fluent methods हर एक this return करती हैं, जो calls को chain करने देता है — new Builder().setA(1).setB(2).build() — अलग statements के बजाय एक readable expression में।

उदाहरण: Fluent Methods

typescript
class RequestBuilder {
  private url = "";
  private method = "GET";
  setUrl(url: string): this { this.url = url; return this; }
  setMethod(method: string): this { this.method = method; return this; }
  build() { return `${this.method} ${this.url}`; }
}
console.log(new RequestBuilder().setUrl("/api").setMethod("POST").build());

Optional Values

Internal state में builder fields को optional मार्क करना उन values को model करता है जिन्हें .build() call करने से पहले set होने की ज़रूरत नहीं है, builder को caller द्वारा unspecified छोड़ी गई किसी भी चीज़ के लिए sensible defaults supply करने देते हुए।

उदाहरण: Optional Values

typescript
class UserBuilder {
  private name = "";
  private age?: number;
  setName(name: string): this { this.name = name; return this; }
  setAge(age: number): this { this.age = age; return this; }
  build() { return { name: this.name, age: this.age ?? 0 }; }
}
console.log(new UserBuilder().setName("Ravi").build());

Validation

एक builder का .build() method यह validate करने की एक natural जगह है कि सभी required fields असल में set की गई थीं, एक invalid object construct होने के बाद के बजाय पहले एक clear error throw करते हुए।

उदाहरण: Validation

typescript
class UserBuilder {
  private name?: string;
  setName(name: string): this { this.name = name; return this; }
  build() {
    if (!this.name) throw new Error("name is required");
    return { name: this.name };
  }
}
console.log(new UserBuilder().setName("Ravi").build());

Builder कब उपयोग करें

Builder pattern तब अपनाएं जब किसी object में कई optional configuration fields हों — यह एक unwieldy multi-argument constructor और एक ready होने से पहले इधर-उधर पास की गई easy-to-misuse partially-filled object दोनों से बचाता है।

उदाहरण: When to Use Builder

typescript
class QueryBuilder {
  private parts: string[] = [];
  select(cols: string): this { this.parts.push(`SELECT ${cols}`); return this; }
  from(table: string): this { this.parts.push(`FROM ${table}`); return this; }
  build() { return this.parts.join(" "); }
}
console.log(new QueryBuilder().select("*").from("users").build());
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक setter method में return this भूल जाना, इसलिए chaining undefined पर रुक जाती है।
  2. Required values set करने से पहले .build() call करना, बिना validation के एक half-built object देते हुए।
  3. build() से internal array खुद return करना, इसलिए बाद की builder calls built object को mutate कर देती हैं।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.