HomeTutorsContact

5 Essential Design Patterns for Node.js Developers

By Gulshan Saini
Published in NodeJS
January 03, 2023
1 min read

Here are five common design patterns with example, used in Node.js:

  1. Factory pattern: The factory pattern is a creational design pattern that provides a way to create objects in a super class, but allows subclasses to alter the type of objects that will be created. This is useful when you need to create objects of different types, but want to centralize the creation process.
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');
  1. Singleton pattern: The singleton pattern is a creational design pattern that ensures that a class has only one instance, and provides a global access point to it. This is useful when you only want to have one instance of a certain class, such as a database connection or a configuration object.
class Database {
  constructor() {
    if (Database.instance) {
      return Database.instance;
    }
    this.connection = new Connection();
    Database.instance = this;
  }
}

const database = new Database();

  1. Prototype pattern: The prototype pattern is a creational design pattern that allows you to clone an object, rather than creating a new instance from scratch. This is useful when creating a new instance is expensive, or when you want to avoid the overhead of creating a new object.
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

  1. Adapter pattern: The adapter pattern is a structural design pattern that converts the interface of a class into another interface that the client expects. This allows classes to work together that couldn’t otherwise because of incompatible interfaces.
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

  1. Command pattern: The command pattern is a behavioral design pattern that allows you to encapsulate a request as an object, allowing you to parameterize clients with different requests, and support undoable operations.
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.


Tags

#nodejs
Previous Article
Different ways to create a copy of an object in JavaScript

Related Posts

NodeJS
Understanding the Event Loop: How Node.js Executes Asynchronous Callbacks
January 04, 2023
5 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

JavaScript
Angular
ReactJS
Typescript
Linux

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media