Contact Me

Builder

 This pattern allows for the creation of complex objects through the use of a step-by-step construction process. This can be useful when the construction process for an object is complex and requires multiple steps, or when the objects being created have many optional parameters that can be included or excluded in the final product.


Here is an example of the builder pattern in JavaScript:


class Product {

constructor(name, price, options) {

  this.name = name;

  this.price = price;

  this.options = options;

}

}

class ProductBuilder {

constructor(name, price) {

  this.name = name;

  this.price = price;

  this.options = [];

}

addOption(option) {

  this.options.push(option);

  return this;

}

build() {

  return new Product(this.name, this.price, this.options);

}

}

const builder = new ProductBuilder('Product', 100);

const product = builder

 .addOption('Option 1')

 .addOption('Option 2')

 .build();

console.log(product);

// Output: Product { name: 'Product', price: 100, options: [ 'Option 1', 'Option 2' ] }


In this example, the Product class represents the object that we want to create, and the ProductBuilder class is responsible for constructing it. The ProductBuilder class has a constructor that takes the name and price of the product as arguments, and has methods for adding options to the product and building the final product.

To use the builder, we first create a new instance of the ProductBuilder class and pass it the name and price of the product. Then, we can call the addOption() method as many times as we want to add options to the product.

Finally, when we are ready to create the product, we call the build() method, which creates and returns a new Product object with the specified name, price, and options.