Tuesday, November 24, 2015

Singleton Class


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();

       }

}


No comments:

Post a Comment

Thank you for your comments.