Sobes.tech
Junior — Middle

What design patterns do you use or know well?

sobes.tech AI

Answer from AI

The following design patterns are often used in Node.js:

  • Singleton — for creating a single instance of an object, for example, for database connection.
  • Factory — for creating objects with different configurations.
  • Observer — for event-driven programming, for example, through EventEmitter.
  • Middleware — in Express.js for processing requests in a chain.
  • Decorator — for extending the functionality of objects without changing their code.

Example of Singleton for database connection:

class Database {
  constructor() {
    if (Database.instance) {
      return Database.instance;
    }
    this.connection = this.connect();
    Database.instance = this;
  }

  connect() {
    // connection logic
    return {};
  }
}

const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true
What design patterns do you use or know well? — Node.js - sobes.tech