Singleton Pattern
Learn about the singleton pattern and how to use it.
We'll cover the following
Description
We have used the singleton pattern in our course already, so it should seem familiar. The singleton design pattern is one of the most commonly used design patterns. It is used when only a single instance of a struct should exist in the entirety of an application’s life cycle. This single instance is called a singleton object. When we want to leverage any functionality of this struct, we will fetch the singleton instance and use its functionality.
Usually, there is a getInstance()
or init()
method defined on the struct for which only one instance needs to be created and stored globally. Once created, every subsequent call to getInstance()
should return the already existing and initialized singleton instance.
Some very popular use cases include creating logger instances and database instances.
When to use
We want to use the singleton pattern in the following cases:
Ensure single instance of resource: Use when we need to ensure there’s only one instance of a class throughout the application.
Centralized access to a global resource: Use when we want a global point of access to a shared resource or state.
Lazy load one resource: Use when lazy initialization of the instance is desirable to optimize performance.
When not to use
We cannot use the singleton resource in the following cases:
Multiple instances required: Avoid using when multiple instances of a class are required in different parts of the application.
Sample code
Let us take a look at a generic singleton pattern implementation that can be borrowed.
Get hands-on with 1400+ tech skills courses.