The Singleton Pattern is a pattern that ensures that there is only ever one single instance of a class.And it provides a global way to get to that instance.
So conversely, The class is going to prevent any other object from instantiating another instance of the class.
USES: Systems like connection pools and threads, logging facilities, preferences and registry objects, different types of device drivers, printers, graphics drivers, even UI dialog or modal controls. There are many resources for which you only need one object.And in fact, if you had more than one, you’d end up with inconsistent or incomplete results or you might even cause an application or system to crash.
This is the Singleton pattern class diagram. We’ve created one class that ensures there’s only ever one instance. And, we used the getInstance method to get access to that instance. The class diagram is simple. Just one class with a getInstance method.
IMPLEMENT CLASSIC SINGLETON PATTERN:
To create a singleton class, we create a private static instance variable for the singleton instance and a private constructor that does nothing. The private constructor ensures that no other class can instantiate a new singleton instance. And the private instance variable ensures that to get an instance of the singleton, we must use the getInstance method. The get Instance method is public and it’s a static method, which means that it is class method. So we’ll have to use the class name, Singleton, to call the method.
In the get Instance method, we first check to see if the Singleton instance already exists by checking to see if the field uniqueInstance is null. If it is, then we need to create the Singleton. Again, because the constructor is private, we can only create the Singleton instance from inside the Singleton class like shown in above code image. We then return the instance of the Singleton. The next time another object calls getInstance, uniqueInstance will not be null, and so getInstance will return the existing Singleton instance. This ensures that only one instance of the singleton class will ever exist.
Also, notice that we are creating the Singleton only when we actually need it. That is, if no object in your code ever calls the Singleton get instance method. then the Singleton is never instantiated. This is called lazy instantiation, and it can come in handy if the class is complex and resource intensive, and should only be instantiated if and when it’s really needed.
CONCLUSION:
- The Singleton pattern should be used when multiple instances of a class should be avoided.
- A Singleton class always has a private constructor.
- If implementing a class using the Singleton Pattern you must ensure it has only one instance and can be globally accessed .
- A Singleton Pattern class will only create an instance if one does not exist yet.