Singleton Pattern
While we are programming, we want to make the code more useful, dynamic, responding, fast-processing, and increase application usability. Because of this matter, we come up with “Patterns”. Here is one of them, Singleton.
Singleton means only one instance of a class or ‘one sun for everyone’. All humans, plants, non-living things can get utilized from the ‘same’ sun. Exactly, in this pattern, we make the application use the same object, and this single-mutation object lives during the entire life-cycle while all objects utilize from the single instantiation of it.
For a real-time example, once I created a method to generate a file name and this file would be used in the entire life-cycle of the program. Right after the file is generated with the UUID name, I would call the same file name in the other methods. This was possible by using a singleton pattern.
As shown in the below very generic, thread-safe utilization, only one thread can execute the method at a time.
public class Singleton {//The pattern ensures that there is only one instance of the class and provides global access to it for the outer world. private static volatile Singleton instance = null; // volatile guarantees the visibility for other threads of writes to that variable private Singleton(){ }
public static synchronized Singleton getInstance(){ //if you add sync in the method name it will be thread-safe if(instance == null){//lazy instantiating
//the singleton instance is not created until the getInstance method is called for the first time. This technique ensures that singleton instances are created only when needed. synchronized (Singleton.class){//first instantiation is null and the object will be created once and it will not be kept as null next time and the same object/value will be used in the other calls if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Here are more examples:
Imagine we are working with the weekdays. Either we want to instantiate the object only once or we call/return one day every time, we use the below Singleton pattern.
Another example is generating, using, calling the file name. See the console creates the object once and you can call many times but the object is still the same one. More examples: driver instantiation, environment instantiation, user instantiation.