Singleton class is that for which, we
can create only one or single instance of the class through the life cycle of
program. In other words, we are restricting user to create multiple instance.
For example, we don’t want to create
connection object if it is already created. We should make our connection class
as singleton class.
Below is code snippet, how to make singleton
class.
/*Singleton Class*/
class TryCatch {
private static TryCatch singleton = new TryCatch();
/*Constructor is
private because we don’t want to create object outside of the class*/
private TryCatch() {
System.out.println("In private constructor…");
}
/* Static
'instance' method */
public static TryCatch
getInstance() {
return singleton;
}
}
/*Main Class*/
public class TryCatchMain {
public static void main(String[] args) {
TryCatch
object = TryCatch.getInstance();
}
}