What is the best/correct way to create a singleton class in java?
One of the implementation I found is using a private constructor and a getInstance() method.
<
just follow the singleton pattern class diagram,
SingletonClass - singletonObject: SingletonClass - SingletonClass() + getObject(): SingletonClass
Key point,
Some code,
public class SingletonClass {
private static boolean hasObject = false;
private static SingletonClass singletonObject = null;
public static SingletonClass getObject() {
if (hasObject) {
return singletonObject;
} else {
hasObject = true;
singletonObject = new SingletonClass();
return singletonObject;
}
}
private SingletonClass() {
// Initialize your object.
}
}