Junior — Middle
Can you explain what the Singleton pattern is and in which cases it is used?
sobes.tech AI
Answer from AI
The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it.
In Node.js, Singleton is often implemented through the module system: when a module is first imported, an object is created, which is then cached and reused in subsequent imports.
Example of a simple Singleton in Node.js:
// logger.js
class Logger {
constructor() {
if (Logger.instance) {
return Logger.instance;
}
this.logs = [];
Logger.instance = this;
}
log(message) {
this.logs.push(message);
console.log(message);
}
}
module.exports = new Logger();
Usage:
const logger1 = require('./logger');
const logger2 = require('./logger');
logger1.log('First message');
console.log(logger1 === logger2); // true
Singleton is useful when you need to control access to resources, such as databases, logging, or configuration, to avoid creating multiple instances and to ensure data consistency.