class DB {
static instance = null;
static getInstance() {
return DB.instance ?? (DB.instance = new DB());
}
}
DB.getInstance() === DB.getInstance(); // trueSingleton ensures only one instance exists β getInstance always returns the same object.
The Singleton pattern restricts a class to have only one instance. One common approach is using a static property to cache the instance.
Challenge: Implement a Database class with a static getInstance() method that returns the same instance every time it's called.
Example:
const db1 = Database.getInstance()
const db2 = Database.getInstance()
db1 === db2 // true