This content originally appeared on DEV Community and was authored by Vishnu KN
In scenarios where the object creation logic is complex or dynamic, the factory design pattern comes in handy.
Imagine someone walking up to a, say, car manufacturing factory, with a well defined request for a car of a certain type (red color, sedan, 818 total horsepower etc) and the factory accepts the request, figures out how to makes it and delivers a concrete product back to the user.
That is the whole idea behind the factory pattern.
So basically, with the factory design pattern, the end result that we want as developers is a way to create objects using a factory class and an abstract instruction like:
objectFactory.createObject(objectType);
So, in order to do something like this, objectFactory should, of necessity, have a static method of the same name.
The reason why it should be static is that we do not want the factory to create a sub-factory and then create the object requested because that would be inefficient
The static method should be very flexible, in the sense that it can take the parameter passed into it and return a concrete instance of an object.
class ObjectFactory {
static createObject(type) {
switch (type) {
case "car":
return new Car();
case "bike":
return new Bike();
default:
throw new Error("Invalid object type");
}
}
}
class Car {
drive() {
console.log("Driving a car");
}
}
class Bike {
ride() {
console.log("Riding a bike");
}
}
// Usage
const myCar = ObjectFactory.createObject("car");
myCar.drive(); // Output: Driving a car
const myBike = ObjectFactory.createObject("bike");
myBike.ride(); // Output: Riding a bike
This content originally appeared on DEV Community and was authored by Vishnu KN