Design Patterns are reusable solutions to common problems that developers encounter while designing and structuring their code. These patterns help in writing maintainable, scalable, and efficient code. Here are some popular JavaScript design patterns:
These design patterns are essential tools for any developer to improve code structure, reusability, and maintainability. The choice of pattern depends on the specific problem you are trying to solve and the design goals you want to achieve in your project.
Module Pattern
Encapsulates private members and provides a way to expose a public API while keeping certain parts of the code private.
const Module = (function() {
let privateVariable = 10;
function privateFunction() {
// Private logic
}
return {
publicVariable: 20,
publicFunction: function() {
// Access privateVariable and privateFunction
}
};
})();
Singleton Pattern
Ensures a class has only one instance and provides a global point of access to that instance.
const Singleton = (function() {
let instance;
function createInstance() {
// Private logic
return {
// Public API
};
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
Factory Pattern
Creates objects without specifying the exact class of object that will be created.
function Product(name, price) {
this.name = name;
this.price = price;
}
function createProduct(name, price) {
return new Product(name, price);
}
Observer Pattern
Defines a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically.
class Subject {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
notify(data) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
update(data) {
// Handle updated data
}
}
Decorator Pattern
Adds new functionality to an object without altering its structure.
class Coffee {
cost() {
return 5;
}
}
function withMilk(coffee) {
const cost = coffee.cost();
return cost + 2;
}
Prototype Pattern
Creates new objects by copying an existing object, known as the prototype.
const carPrototype = {
wheels: 4,
start() {
console.log('Car started.');
}
};
function createCar() {
const car = Object.create(carPrototype);
return car;
}
Command Pattern
Encapsulates a request as an object, allowing parameterization of clients with queues, requests, and operations.
class Command {
constructor(receiver) {
this.receiver = receiver;
}
execute() {
this.receiver.action();
}
}
class Receiver {
action() {
// Perform action
}
}
const receiver = new Receiver();
const command = new Command(receiver);
command.execute();
Leave a Reply