Skip to main content

How to write singleton class in java

Singleton class  












public class MySingleton {


private MySingleton(){
System.out.println("Creating new Instance");
}


private static class LazyHolder{
private static final MySingleton INSTANCE=new MySingleton();
}

public static MySingleton getInstance(){
return LazyHolder.INSTANCE;
}

public void printSingleton(){
System.out.println("inside print singleton");
}



}


usage :

MySingleton.getInstance().printSingleton();
MySingleton.getInstance().printSingleton();
MySingleton.getInstance().printSingleton();
MySingleton.getInstance().printSingleton();


you can check yourself the Mysingleton class constructor will invokes only once .

Comments

  1. Another great articles and very interesting to read,thanks for sharing that wonderful useful information,given program coding was very excellent and easily observe all provided information.
    ios training in chennai

    ReplyDelete
  2. Someone essentially lend a hand to make severely posts I would state. That is the very first time I frequented your website page and thus far? I surprised with the analysis you made to create this particular submit incredible. Fantastic job!

    Online Training in Chennai

    ReplyDelete
  3. Thank you for sharing such a nice and interesting blog with us.very unique and recommanded I would like to suggest your blog in my student circle

    java training in hyderabad
    java training institute in hyderabad
    java training in ameerpet

    ReplyDelete

Post a Comment