The Singleton pattern assures that a class has only one instance and provides a global point of access for it. Sometimes, singleton patterns is considered as the antipattern because high usage of this can have more cons than the pros. There are two types of singleton pattern:
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor to prevent instantiation
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
In the above code we can see that the class Singleton prevents instantiation of it’s objects via the constructor and allows only one instance to be present via the factory method getInstance(). The method will create an instance if no instance is created else it will return the previously created instance.
For multi-threaded applications we sometimes could also use synchronized keyword for the getInstance() factory method. The usage of this keyword ensures, only one thread can execute this factory method at a specific point of time.
Apart from the singleton design patterns, there are more design patterns used in computer science. You can read more about them here.