0% found this document useful (0 votes)
2 views

Design Patterns Example

disng pattrn examples

Uploaded by

suchit kapale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Design Patterns Example

disng pattrn examples

Uploaded by

suchit kapale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

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)

You might also like