Singleton class Explained
Posted On
Posted By admin
Singleton is a design pattern. A singleton class is a class for which only one object can be created. You can create a singleton class by using a private constructor. The following code snippet demonstrates this:
private static Singleton singletonInstance; private Singleton(){ } public static Singleton getInstance(){ if (singletonInstance == null){ singletonInstance = new Singleton(); } return singletonInstance; }
Here, we have a private constructor and a public getInstance method. The getInstance checks if an instance already exists. If an instance does not exist, it creates one using the private constructor. If an instance exists, it just returns it. So this method ensures that there is only one instance of the Singleton class. Any external class that needs an instance of the Singleton class, should invoke the getInstance method.
If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my Java course here
Also, if you'd like to test your Java knowledge, do check out my practice tests course here
Also, if you'd like to test your Java knowledge, do check out my practice tests course here
If you like this post, please do let me know via the comments box below. You can also connect with me via my Facebook Page or subscribe to my Youtube channel!