Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Last active September 17, 2019 21:19
Show Gist options
  • Select an option

  • Save YozhEzhi/f66b3505ac0d5a7a8dc4c62083eeed1c to your computer and use it in GitHub Desktop.

Select an option

Save YozhEzhi/f66b3505ac0d5a7a8dc4c62083eeed1c to your computer and use it in GitHub Desktop.
Singleton in Typescript
class Singleton {
private static instance: Singleton;
private constructor() {
// do something construct...
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
// ... any one time initialization goes here ...
}
return Singleton.instance;
}
someMethod() { }
}
const something = new Singleton() // Error: constructor of 'Singleton' is private.
const instance = Singleton.getInstance() // do something with the instance...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment