Sometimes, having multiple instances of a class make things confusing, wasteful or logically wrong. In such instances, the factory design pattern comes handy.
In the construction of a car, each car has only one chassis. One set of workers may request access to the chassis to add wheels, the other set might want the chassis to work on gears and an other set of workers might want to work on the windshield. But they all get the same chassis. When it is first requested, the chassis is created. For all subsequent requests, the same chassis is returned.
Here is how it look like in code:
class Chassis {
constructor() {
if (Chassis.instance) {
return Chassis.instance;
}
console.log("🚗 New chassis created");
Chassis.instance = this;
}
}
const teamA = new Chassis(); // 🚗 New chassis created
const teamB = new Chassis(); // returns existing chassis
const teamC = new Chassis(); // same instance
console.log(teamA === teamB && teamB === teamC); // true
Top comments (0)