Creating a singleton

Sometimes, we may need to have a single occurrence of an object throughout the application life. Consider, for example, a configuration manager or a cache manager. Since they provide a global point of access to an internal or external resource, they need to be implemented in a way so that only one instance must exist, that is, they need to be implemented as a singleton.

The singleton pattern is one of the simplest design patterns—it involves only one entity which is responsible for making sure it creates not more than one instance and provides a global point of access to itself. For a class-based language, this means that a class can be instantiated only one time and any attempt to create a new instance of the class returns ...

Get Mastering JavaScript Object-Oriented Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.