Junior — Middle
Can you name the main design patterns you have encountered in your practice?
sobes.tech AI
Answer from AI
Common design patterns encountered in Node.js practice:
- Singleton — ensures a class has only one instance and provides a global point of access to it.
- Factory — creates objects without specifying the exact class, allowing the type of object to be determined at runtime.
- Observer — allows objects to subscribe to events and receive notifications when they occur.
- Middleware — often used in Express.js to handle requests through a chain of functions.
- Decorator — dynamically extends the functionality of an object without changing its structure.
Example of Singleton in Node.js:
class Logger {
constructor() {
if (Logger.instance) {
return Logger.instance;
}
Logger.instance = this;
}
log(message) {
console.log(message);
}
}
const logger1 = new Logger();
const logger2 = new Logger();
console.log(logger1 === logger2); // true
These patterns help in writing more structured, maintainable, and extendable code.