I understand that Singelton helps to instantiate only one class AT A TIME. I try to learn how to Design for Singleton function in java. I want to know it better to understand Kernel. So I try to do this following, but I like to know if it’s the only way to come up with private constructor.
public class Singleton {
private static Singleton instance = null;
private Singleton() { }
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton ();
}
return instance;
}
}
4
yes, to create a Singleton class, you have to use the private constructor as it is the only way to prevent another class from creating an instance of your class.
public class Singleton {
private static Singleton instance = null;
private Singleton() { }
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton ();
}
return instance;
}
}
1
on of the biggest misconceptions that I see is that lazy instantiation is needed for all singletons, it isn’t.
Java has it’s own lazy loading of classes that will allow for lazy instantiation when the class is first needed:
public class Singleton {
private static Singleton instance = new Singleton ();
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
often this is all you need for lazy instantiation of a singleton in java
If I understand your question correctly, then yes, to create a Singleton class, you have to use the private constructor as it is the only way to prevent another class from creating an instance of your class.
If your question is another way of getting around getInstance(), then it is also possible to use a private static inner class and either use that to store the reference as in this android related question.
public class Singleton {
private Singleton() {}
public static synchronized Singleton getInstance() {
return Implementation.INSTANCE;
}
private static class Implementation {
public static final Singleton INSTANCE = new Singleton();
}
}
1