Skip to content

Singleton Pattern

The Singleton pattern ensures a class has only one instance and provides a global point of access to it.

class Database {
constructor() {
if (Database.instance) {
return Database.instance;
}
this.connection = null;
Database.instance = this;
}
connect(url) {
this.connection = url;
console.log(`Connected to ${url}`);
}
query(sql) {
if (!this.connection) throw new Error('Not connected');
return `Result of: ${sql}`;
}
}
const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true
  • Single instance guarantee
  • Often controversial — can make testing difficult
  • Useful for configuration, logging, database connections