Curriculum
In Java, the Singleton pattern is a design pattern that ensures that a class has only one instance, and provides a global point of access to that instance. The Singleton pattern is useful in situations where you need to restrict the number of instances of a class, such as when you need to control access to a shared resource or manage a system-wide configuration.
Here’s an example of a Singleton class in Java:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
// private constructor to prevent instantiation
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void showMessage() {
System.out.println("Hello World!");
}
}
In this example, the Singleton class has a private constructor to prevent instantiation and a getInstance() method that returns the singleton instance. The getInstance() method checks if an instance of the class has already been created, and if not, it creates a new instance of the class. The showMessage() method is a public method of the class that can be called to output a message.
Here are some rules to keep in mind when working with Singleton classes in Java:
Serializable interface and defining a readResolve() method.Overall, Singleton classes can be useful in Java when you need to ensure that there is only one instance of a class, such as when you need to control access to a shared resource or manage a system-wide configuration. By restricting the number of instances of a class, you can help to ensure that your code is more maintainable and easier to test.