Created
March 11, 2021 10:17
-
-
Save viveknaskar/7a4ce9e68720894631cd7d0279963905 to your computer and use it in GitHub Desktop.
An illustration of Singleton Design Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Singleton is a design pattern by which you create a singleton class that has only one instance | |
* at any time | |
* | |
*/ | |
public class SingletonExample { | |
private static SingletonExample single_instance = null; | |
public String msg; | |
/** | |
* Making the constructor as private | |
*/ | |
private SingletonExample() { | |
msg= "Hello World!"; | |
} | |
/** | |
* Static method to create instance of Singleton class | |
* @return single object of 'SingletonExample' class | |
*/ | |
public static SingletonExample getInstance() { | |
/** | |
* Ensuring only one instance is created | |
*/ | |
if (single_instance == null) | |
single_instance = new SingletonExample(); | |
return single_instance; | |
} | |
public static void main(String[] args) { | |
/** | |
* Instantiating SingletonExample class with variable 'singletonObject' | |
*/ | |
SingletonExample singletonObject = SingletonExample.getInstance(); | |
System.out.println(singletonObject.msg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment