Last active
September 17, 2019 21:19
-
-
Save YozhEzhi/f66b3505ac0d5a7a8dc4c62083eeed1c to your computer and use it in GitHub Desktop.
Singleton in Typescript
This file contains hidden or 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
| 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