أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.
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;
}
}