Design Patterns Example: Factory and
Singleton
Factory Pattern Example
In the Factory Pattern, a factory class is responsible for creating instances of different
classes.
Here is a simple example:
// Product classes (Different vehicle types)
class Car {
constructor() {
this.type = 'Car';
}
drive() {
console.log('Driving a car.');
}
}
class Bike {
constructor() {
this.type = 'Bike';
}
ride() {
console.log('Riding a bike.');
}
}
// Factory class to create vehicles
class VehicleFactory {
static createVehicle(vehicleType) {
switch (vehicleType) {
case 'car':
return new Car();
case 'bike':
return new Bike();
default:
throw new Error('Unknown vehicle type.');
}
}
}
// Client code using the factory to create objects
const myCar = VehicleFactory.createVehicle('car');
myCar.drive(); // Output: Driving a car.
const myBike = VehicleFactory.createVehicle('bike');
myBike.ride(); // Output: Riding a bike.
Singleton Pattern Example
In the Singleton Pattern, only one instance of a class is allowed, and this instance is reused.
Here is a simple example:
class Singleton {
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this.data = 'Singleton instance data';
Singleton.instance = this; // Cache the instance
}
getData() {
return this.data;
}
}
// Client code
const instance1 = new Singleton();
console.log(instance1.getData()); // Output: Singleton instance data
const instance2 = new Singleton();
console.log(instance1 === instance2); // Output: true (both refer to the same instance)