Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

How many ways we can write Singleton Class in Java?

user-image
Question ajoutée par Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date de publication: 2014/04/23
Maria Thomas
par Maria Thomas , Tech Lead , J P Morgan Chase

There are four known ways to write Singleton class in Java.

1. The classic often used one : Create a private constructor and call this inside getInstance() method which is then invoked by the calling class. This should be synchronized using double checked locking. This comes in lazy initialization since the instance is created only when the method is first called.

2. Create a public static final field for the Singleton instance and call the constructor. This is created during class loading. This comes under early initialization.

public static SingletonInstance instance = new SingletonInstance();

3. Using Enums

Eg: public enum Singleton{ INSTANCE }

4. Creating static inner class wherein creation of the instance is done. This is called Singleton Helper model.

Eg:

public class SingletonInstance{

      private SingletonInstance(){}

      private static class SingletonHelper{

          private static final SingletonInstance instance = new SingletonInstance();

      }      

      public SingletonInstance getInstance(){

         return SingletonHelper.instance;

      }

}

More Questions Like This

Avez-vous besoin d'aide pour créer un CV ayant les mots-clés recherchés par les employeurs?