-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathSingleton.js
36 lines (29 loc) · 909 Bytes
/
Singleton.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
Singleton is a special creational design pattern where only one instance of a class can exist. It works like this - if no instance of the singleton class exists then a new instance is created and returned but if an instance already exists then the reference to the existing instance is returned.
A perfect real-life example would be that of mongoose (the famous Node.js ODM library for MongoDB). It utilizes the singleton pattern.
*/
class Database {
constructor(data) {
if (Database.exists) {
return Database.instance;
}
this._data = data;
Database.instance = this;
Database.exists = true;
return this;
}
getData() {
return this._data;
}
setData(data) {
this._data = data;
}
}
// usage
/*
const mongo = new Database('mongo');
console.log(mongo.getData()); // mongo
const mysql = new Database('mysql');
console.log(mysql.getData()); // mongo
*/
module.exports = Database;