Шаблон TypeScript Builder: шаг за шагом создаем сложные объекты

Шаблон ts builder относится к реализации TypeScript шаблона проектирования Builder. Шаблон «Строитель» — это шаблон творческого проектирования, который позволяет шаг за шагом создавать сложные объекты. Это полезно, когда у вас есть объект со множеством необязательных параметров и вы хотите предоставить ясный и краткий способ его создания.

Вот пример реализации шаблона компоновщика в TypeScript:

class Product {
  private name: string;
  private price: number;
  private description: string;
  constructor(name: string, price: number, description: string) {
    this.name = name;
    this.price = price;
    this.description = description;
  }
// Getters for the private properties
  getName(): string {
    return this.name;
  }
  getPrice(): number {
    return this.price;
  }
  getDescription(): string {
    return this.description;
  }
}
class ProductBuilder {
  private name: string;
  private price: number;
  private description: string;
  setName(name: string): ProductBuilder {
    this.name = name;
    return this;
  }
  setPrice(price: number): ProductBuilder {
    this.price = price;
    return this;
  }
  setDescription(description: string): ProductBuilder {
    this.description = description;
    return this;
  }
  build(): Product {
    return new Product(this.name, this.price, this.description);
  }
}
// Usage example
const product = new ProductBuilder()
  .setName("Example Product")
  .setPrice(9.99)
  .setDescription("This is an example product.")
  .build();
console.log(product.getName()); // Output: Example Product
console.log(product.getPrice()); // Output: 9.99
console.log(product.getDescription()); // Output: This is an example product

В приведенном выше примере у нас есть класс Productс частными свойствами для name, priceи description. Класс ProductBuilderпредоставляет методы для установки этих свойств одно за другим. Каждый метод установки возвращает сам экземпляр компоновщика, что позволяет создавать цепочки методов. Метод build()создает и возвращает новый экземпляр Product, используя предоставленные значения.