Junior — Middle
Should a static method be used when implementing the Singleton pattern?
sobes.tech AI
Answer from AI
Yes, when implementing the Singleton pattern in Java, a static method is usually used to obtain the single instance of the class. This is because a static method allows controlling the creation of the object and guarantees that the instance will be created only once.
A classic implementation of Singleton using a static method and lazy initialization:
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Here, getInstance() is a static method that returns the only instance of the class. Using a static method is convenient because it does not require creating an object to call it and provides a global access point.