If I want to define Singleton
, then it’ll be something like this:
A Singleton is a software design pattern that guarantees a class has one instance only and a global point of access to it is provided by that class.
Singleton Pattern ensures that only one instance would be created and it would act as a single point of access thereby ensuring thread safety.
In java code, it’ll look like this:
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
But the above codes are dangerous, especially if it’s used in different threads. If two threads access this singleton at a time, two instances of this object could be generated.
class Singleton {
private static Singleton instance = null;
private Singleton() {
}
private synchronized static void createInstance() {
if (instance == null) {
instance = new Singleton();
}
}
public static Singleton getInstance() {
if (instance == null) createInstance();
return instance;
}
}