Skip to content

Instantly share code, notes, and snippets.

@micksatana
Created October 31, 2020 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micksatana/1441df01fb692cdb96a1a09be249a39b to your computer and use it in GitHub Desktop.
Save micksatana/1441df01fb692cdb96a1a09be249a39b to your computer and use it in GitHub Desktop.
Example - Singleton DP in Node.js
/**
* 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