The Singleton pattern encapsulates a shared resource within a single unique class instance. This instance arbitrates access to the resource and storage-related state information. A class method provides the reference to this instance, so there is no need to pass the reference around Any object that has access to the Singleton’s class header can use the Singleton.
This design pattern defines the structure of a class that can have only one instance. A Singleton encapsulates a unique resource and makes it readily available throughout the application. The resource might be hardware, a network service, a persistent store, or anything else that can be modeled as a unique object or service. Singletons may often be modeled as a server within the application that accepts requests to send, store, or retrieve data and configure the resource state.
Implementation of the Singleton pattern often typically creates a single object using the factory method, and this instance/object is called a shared instance in most cases. Since the access to the instance is passed on though a class method, the need to create an object is eliminated.
Pros and Cons
Singletons are not the answer to every problem. Like any tool, they can be short in supply or can be overused. Some developers are critical of Singletons for various reasons. We will examine this critique and discuss ways to address them briefly. The criticisms, for the most part, fall into two categories:
Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.
Singletons create hidden dependencies: As the Singleton is readily available throughout the code base, it can be overused. Moreover, since its reference is not completely transparent while passing to different methods, it becomes difficult to track.
To avoid these complications, when considering the Singleton pattern, you should make certain that the class is a Singleton. Also, while thinking of designing the Singleton design pattern, keep testing in mind and use dependency injection whenever possible, which means: try to pass the singleton as a parameter to the initializer whenever possible.
Thank you for reading, please share it if you found it useful!