Created
October 31, 2020 03:56
-
-
Save micksatana/1441df01fb692cdb96a1a09be249a39b to your computer and use it in GitHub Desktop.
Example - Singleton DP in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This is a mocked connection class. Think of it like a class to create a connection to database. | |
*/ | |
class Connection { | |
status = ''; | |
constructor() { | |
console.log('instantiated'); | |
this.status = 'connected'; | |
console.log(this.status); | |
} | |
} | |
/** | |
* SingletonConnection | |
* We can apply Singleton DP with the Connection class, | |
* and instantiate x and y to see status changed in x is also changed in y. | |
*/ | |
class SingletonConnection { | |
static _instance; | |
static getInstance() { | |
if (!SingletonConnection._instance) { | |
SingletonConnection._instance = new Connection(); | |
} | |
return SingletonConnection._instance; | |
} | |
} | |
// x instantiates a connection | |
const x = SingletonConnection.getInstance(); | |
// y is created later, Singleton design pattern will use the same instance previously instantiated | |
const y = SingletonConnection.getInstance(); | |
// So when x is closed | |
x.status = 'closed'; | |
console.log('x.status', x.status); | |
// y also closed (as it refers to the same instance) | |
console.log('y.status', y.status); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment