Interview question
How do you implement the Singleton pattern in JavaScript? JavaScript में Singleton pattern कैसे implement करें?
Answer
The Singleton pattern ensures a class has only one instance and provides a global point of access to it - useful for things like a single database connection or a shared configuration object.
// Singleton using a class with a static instance check
class Database {
static #instance;
constructor() {
if (Database.#instance) {
return Database.#instance; // return the existing instance instead of creating new
}
this.connection = 'Connected to DB';
Database.#instance = this;
}
query(sql) {
return `Running: ${sql}`;
}
}
const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true - same instance, second 'new' returned the first
// Singleton using a static getInstance() method (more explicit, common pattern)
class Logger {
static #instance;
static getInstance() {
if (!Logger.#instance) {
Logger.#instance = new Logger();
}
return Logger.#instance;
}
log(message) {
console.log(`[LOG]: ${message}`);
}
}
const logger1 = Logger.getInstance();
const logger2 = Logger.getInstance();
console.log(logger1 === logger2); // true
// Simplest Singleton using a module - the module system itself provides the guarantee
// config.js
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000
};
export default config;
// Every file that imports config.js gets the SAME object reference
// because ES modules are cached/singleton by nature
// Caution: singletons introduce global state and hidden coupling,
// making testing harder - use sparingly and consider dependency injection insteadSingleton pattern यह सुनिश्चित करता है कि class का सिर्फ एक instance हो और उस तक global access दे - single database connection या shared config जैसी चीज़ों के लिए उपयोगी।
// Static instance check से Singleton
class Database {
static #instance;
constructor() {
if (Database.#instance) {
return Database.#instance;
}
this.connection = 'Connected to DB';
Database.#instance = this;
}
query(sql) {
return `Running: ${sql}`;
}
}
const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true - same instance
// getInstance() static method से (ज़्यादा common pattern)
class Logger {
static #instance;
static getInstance() {
if (!Logger.#instance) {
Logger.#instance = new Logger();
}
return Logger.#instance;
}
log(message) {
console.log(`[LOG]: ${message}`);
}
}
const logger1 = Logger.getInstance();
const logger2 = Logger.getInstance();
console.log(logger1 === logger2); // true
// Module से सबसे सरल Singleton
// config.js
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000
};
export default config;
// हर file जो import करती है वो same object reference पाती है
// सावधानी: singletons global state और hidden coupling लाते हैं,
// testing मुश्किल बनाते हैं - इस्तेमाल संभालकर करेंWas this answer clear?