In Java, a singleton class is a class that can only be instantiated once, and provides a single instance of itself to the rest of the program. The purpose of a singleton class is to ensure that there is only one instance of the class in the program, and to provide a global point of access to that instance.
To implement a singleton class in Java, we need to ensure that the class has a private constructor, a private static instance variable, and a public static method that returns the instance variable. Here’s an example:
public class Singleton {
private static Singleton instance;
private Singleton() {
// Private constructor to prevent instantiation from outside the class
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Main {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // Output: true
}
}
In this example, we define a Singleton class with a private constructor and a private static instance variable. We also define a public static method called getInstance() that returns the instance variable, creating it if it hasn’t already been created.
To create an instance of the Singleton class, we call the getInstance() method on the class itself. The first time this method is called, the instance variable will be null, so a new instance of the Singleton class will be created. Subsequent calls to the getInstance() method will return the same instance of the class.
In the Main class, we create two instances of the Singleton class using the getInstance() method, and check if they are the same object using the == operator. Because the Singleton class ensures that there is only one instance of the class in the program, the two variables s1 and s2 will reference the same object, and the output will be true.
In summary, a singleton class in Java is a class that can only be instantiated once, and provides a single instance of itself to the rest of the program. To implement a singleton class, we need to ensure that the class has a private constructor, a private static instance variable, and a public static method that returns the instance variable. When the method is called, it creates the instance if it hasn’t already been created, and returns the existing instance otherwise.