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:
}
}
}
}
}
}
}
}
}
productA.
// Output: ConcreteProductA operation.
productB.
// 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.