Contact Me

Factory

 This pattern provides an interface for creating objects in a super class, but allows subclasses to alter the type of objects that will be created. This can be useful when you want to create objects without specifying the exact class of object that will be created, and when you want to change the type of objects that will be created at runtime.


Here is an example of the factory pattern in JavaScript:


class Product {

operation() {}

}

class ConcreteProductA extends Product {

operation() {

  console.log('ConcreteProductA operation.');

}

}

class ConcreteProductB extends Product {

operation() {

  console.log('ConcreteProductB operation.');

}

}

class Creator {

createProduct(productType) {

  if (productType === 'A') {

   return new ConcreteProductA();

  } else if (productType === 'B') {

   return new ConcreteProductB();

  }

}

}

const creator = new Creator();

const productA = creator.createProduct('A');

const productB = creator.createProduct('B');

productA.operation();

// Output: ConcreteProductA operation.

productB.operation();

// Output: ConcreteProductB operation.


In this example, the Product class is an abstract class that defines the interface for a product, and the ConcreteProductA and ConcreteProductB classes are concrete implementations of the Product class that represent specific types of products. The Creator class is a class that has a createProduct() method for creating products of a specific type.

To use the factory pattern, we create an instance of the Creator class, and then call the createProduct() method on it, passing in the type of product that we want to create. The createProduct() method will return an instance of the appropriate product class, allowing us to create objects without specifying the exact class of object that will be created.

This allows us to change the type of objects that will be created at runtime by simply passing a different value to the createProduct() method.