singleton in javascript
class Singleton
{
constructor()
{
if (!Singleton.instance)
{
Singleton.instance = this;
}
return Singleton.instance;
}
getInstance()
{
return this.instance;
}
}
test
const testA = new Singleton();
const testB = new Singleton();
console.log(testA === testB); // true
singleton example (db connection)
const URL = "db_url";
const createConnection = url => ({"url" : url});
class DB
{
constructor(url)
{
if (!DB.instance)
{
DB.instance = createConnection(url);
}
return DB.instance;
}
connect()
{
return this.instance;
}
}
profits of singleton
save cost of creating instance.
disadvantage of singleton
high coupling
(can be resolved DI(dependency injection))
Top comments (0)