Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as
public class Singleton { private static Singleton ref; private Singleton() { } public static Singleton getInstance() { if (ref == null) { ref = new Singleton(); } return ref; } }
suddenly he told me this is old way of writing the class. Can any one please help me why he told like that.
Eager initialization: In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a Singleton class. By making the constructor as private you are not allowing other class to create a new instance of the class you want to create the Singleton.
Example. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton.
The first thing which comes to my mind when creating a singleton is enum
. I generally use enum to implement singleton:
enum Singleton { INSTANCE; }
One benefit you get with using enum is with Serialization.
With singleton class, you would have to make sure that serialization and deserialization doesn't create a new instance by implementing the readResolve()
method, while this is not the case with enum.
Using class you should create the singleton like this:
public final class Singleton implements Serializable { // For lazy-laoding (if only you want) private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton() { if (SingletonHolder.INSTANCE != null) { // throw Some Exception } } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } // To avoid deserialization create new instance @SuppressWarnings("unused") private Singleton readResolve() { return SingletonHolder.INSTANCE; } }
Latest Standard Solutions:
Core java with Managed Beans / CDI
@ApplicationScoped public class MySingleton { ... }
EJB Lite (JEE6)
@Singleton public class MySingleton { ... }
Prior Recommendation (from 'Effective Java 2'):
Use an enum, with a single bogus enumeration constant e.g. INSTANCE. Data fields and methods can be either static or non-static (instance) - the two behave equivalently, since there's only one instance
Advantages:
Disadvantages (compared with above Standard Solutions):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With