Singleton

The main thing you need to know about the singleton pattern is that it only allows a class to have a single instance and it uses a global variable to store that instance. You'll use lazy loading to make sure that there is only one instance of the class because it will only create the class when you need it. That prevents multiple instances from being created. Most of the time this gets implemented in the constructor.

An example of a singleton that you probably use all the time is a state object in JavaScript. If you work with some of the front-end frameworks like React or Angular, you know all about how the parent component's state gets distributed to the child components. This is a great example of singletons in action because you never want more than one instance of that state object.

Last updated

Was this helpful?