NodeJS
Understanding the Event Loop: How Node.js Executes Asynchronous Callbacks
January 04, 2023
5 min
Here are five common design patterns with example, used in Node.js:
class VehicleFactory { createVehicle(type) { if (type === 'car') { return new Car(); } else if (type === 'truck') { return new Truck(); } } } class Car { // implementation details } class Truck { // implementation details } const factory = new VehicleFactory(); const car = factory.createVehicle('car'); const truck = factory.createVehicle('truck');
class Database { constructor() { if (Database.instance) { return Database.instance; } this.connection = new Connection(); Database.instance = this; } } const database = new Database();
class Sheep { constructor(name, category = 'Mountain Sheep') { this.name = name; this.category = category; } clone() { return new Sheep(this.name, this.category); } } const original = new Sheep('Jolly'); const cloned = original.clone(); console.log(cloned.name); // Jolly
class OldCalculator { operate(x, y, operation) { if (operation === 'add') { return x + y; } else if (operation === 'subtract') { return x - y; } } } class NewCalculator { add(x, y) { return x + y; } subtract(x, y) { return x - y; } } class CalculatorAdapter { constructor() { this.calc = new NewCalculator(); } operate(x, y, operation) { if (operation === 'add') { return this.calc.add(x, y); } else if (operation === 'subtract') { return this.calc.subtract(x, y); } } } const oldCalc = new OldCalculator(); console.log(oldCalc.operate(10, 5, 'add')); // 15 const newCalc = new NewCalculator(); console.log(newCalc.add(10, 5)); // 15 const adapter = new CalculatorAdapter(); console.log(adapter.operate(10, 5, 'add')); // 15
class BankAccount { constructor(balance = 0) { this.balance = balance; this.commands = []; } deposit(amount) { this.balance += amount; this.commands.push(() => this.deposit(amount)); } withdraw(amount) { if (this.balance >= amount) { this.balance -= amount; this.commands.push(() => this.withdraw(amount)); } else { console.log('Insufficient funds'); } } undo() { const command = this.commands.pop(); if (command) { command(); } } } const account = new BankAccount(100); account.deposit(50); account.withdraw(25); console.log(account.balance); // 125 account.undo(); console.log(account.balance); // 100
These are just a few examples, but there are many other design patterns that can be useful when developing applications with Node.js.