Junior — Middle
What steps are needed to initialize a Singleton component after defining the class?
sobes.tech AI
Answer from AI
To initialize a Singleton component after defining the class, the following steps are usually performed:
-
Create a private static instance of the class inside the class itself. This ensures that the instance will be unique.
-
Define a private constructor to prevent creating objects from outside.
-
Provide a public static method (e.g.,
getInstance()) that returns the single instance of the class. It initializes the instance on the first call and returns the already created one on subsequent calls.
Example in Java:
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Thus, initialization occurs on the first call to getInstance(). If you want to initialize immediately after defining the class, you can use a static block or initialize instance directly at the declaration.