Junior — Middle
What design patterns have you used in your practice?
sobes.tech AI
Answer from AI
In practice with Node.js, the following design patterns are often used:
- Module Pattern — for organizing code into separate files and exporting functionality.
- Factory Pattern — for creating objects with different configurations.
- Singleton — for creating a single instance of an object, such as a database connection.
- Observer (Listener) — for implementing events and subscriptions, often through EventEmitter.
- Middleware — in Express.js for processing requests in a chain.
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
These patterns help write more structured, maintainable, and scalable code.