DEV Community

loading...

Discussion on: Singleton in JavaScript

Collapse
tomekbuszewski profile image
Tomek Buszewski Author

I haven't used singletons in a while, but I remember it being quite useful when I was building services for sensitive DOM manipulation and listening. You create a listener in a constructor and this guarantee that this is the only one available. But, like I said, this can be done in a myriad of other ways and I have written this strictly as an informative post.

Collapse
coly010 profile image
Colum Ferry

Angular uses Singletons a lot. They provide a TypeScript decorator called: @Injectable which turns whichever class is decorated into a Singleton.

The use-case in Angular is logic services. Sure you can use them to maintain state in your App but it can be messy, bug-prone and hairy if you do not take great care in doing so.
However, on the flip side, if you have a class whose function is to provide pure methods or to fetch data from a data-source, then why should you need multiple instances of this class.

In fact, having multiple instances will take up memory within your app. This could be dangerous!
If you do maintain state in your service, perhaps you want to know the loggedInUser, having a singleton for this makes perfect sense. You should only have one logged in user and therefore your singleton will only ever return this one user.

Collapse
dance2die profile image
Sung M. Kim

If I may, I'd like to shamelessly plug my post about another valid usage of Singleton pattern 😛

The gist is that, Singleton pattern works great in combination with a Null pattern (where the null object is implemented as a singleton).