What is the singleton pattern?
In the programming language Java, only the package that contains the Singleton’s class can create the instance of the singleton class. Specifically, only that particular class in that particular package can create the single instance of that singleton class. If one instance already exists, the singleton class won’t allow the creation of another instance. Other classes within and outside the package that contains the singleton class can obtain that instance and its properties. These same different classes can also manipulate or alter the properties of the singleton instance.
In the above code, the constructor of the class is private. This means that only the singleton class in the particular package that contains the class can invoke the constructor. A constructor in object-oriented programming dynamically allocates memory space for an “object” or this class instance and creates an instance of the class. This class instance is stored within the memory that was dynamically allocated for the class instance. The one instance of the class is private and also static meaning that only this singleton class has direct access to the singleton instance.
Also when a property is designated as static it describes that class. In other words, all instances of that class have those properties. Other classes in the same package and outside the same package as the singleton class have access to that instance. To ensure that only one thread at a time is executing the getter function getInstance the synchronized access modifier is added.
To learn more about the Singleton pattern I recommend reading Head First: Design Patterns by Eric Freeman and Elisabeth Robson. Another good resource is the GeekForGeeks article on the Singleton design pattern here. To view more of our blogs visit the blog section of our website here.