0
    Public class Singleton{

             //private static ref
             private Static Singleton uniqueInstance; 

              //private constructor
              private Singleton(){
              }

             public static Singleton getInstance{

             if(uniqueInstance==null){

            uniqueInstance= new Singleton();
             }

           return uniqueInstance;

           }

}

The above class is my current implementation of the traditional use of singleton. How would I implement the enum version of singleton on this class? And what are its benefits over the traditional?

I.e. how does this work:

public enum Foo {
   INSTANCE;
}

1 Answers1

0

As per Joshua Bloch Creating a sigleton using enum is guaranteed way that a class be singleton. And even using reflection multiple instances cannot be created. But some people don't like to implement sigletons this way. and it's topic of debate.

By the way the code snippet you have is not thread safe. More than one threads can go into getInstance method at the same time and your sigleton pattern will break. If you need more explanation how let me know in the comments.

See this link it explains with code how your sigleton pattern can break if it's not implemented as enum.

vkg
  • 1,839
  • 14
  • 15