Junior — Middle
Can you explain the Singleton design pattern and its application?
sobes.tech AI
Answer from AI
Singleton is a design pattern that guarantees a class has only one instance and provides a global point of access to it.
Application:
- When a single object is needed, for example, for managing configuration, logging, or database connection.
- To avoid creating multiple instances that may consume resources or lead to inconsistency.
Example of implementing Singleton in Node.js:
class Singleton {
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this.value = Math.random();
Singleton.instance = this;
}
}
const a = new Singleton();
const b = new Singleton();
console.log(a === b); // true
Thus, when trying to create a new instance of the Singleton class, the same instance is always returned.