What is Singleton Design Pattern?

Let’s begin with a straightforward outline of the singleton pattern. Singleton design pattern is considered as one of the most commonly used and simplest design patterns in object-oriented programming. The purpose of this design pattern is to restrict the object creation by limiting the initialization of a particular class by single instance throughout the Java Virtual Machine.

There are circumstances where we use single object instance multiple times. For an example think of creating a connection for database for multiple users. If an object has to be created for each user request, there will be multiple objects for one single class. This will cause numerous issues for the application, especially on performance. Singleton design pattern is used to overcome such conflicts by the developers.

Before we move into the implementation of the singleton, will look into the key points that we must remember the principles of the Singleton that developers violate,

There are possibilities where the Singleton could have arguments but as the best practices when creating an instance for singleton design pattern, Developers should avoid having any argument for the instance of the particular class.

Technically to create an instance for an object we use the keyword “NEW” but will this applicable for every scenario? How do we create an object outside of the class when we create a private constructor for a particular class? Well, if you are looking for the answer for the above questions here it is.

Early initialization and Lazy initialization are the two methods where singleton class could be instantiated.

Early initialization : In early initialization the class is initialized at the class loading time.

Lazy initialization : Lazy initialization is generally used in creation of singleton class, in this method the class is initialized only when it is required.

The above implementation illustrates how singleton design pattern is implemented in a DBManager class. To prevent the object modification from the outside of the class, the “dbManager” is set to private and volatile and to avoid are circumstances where framework like reflection may interfere with this and create an instance manually .

Synchronized ensures that there won’t be any additional instantiation even though there are more than one thread access the “getDBManager ()” method concurrently.

Happy coding!!

References:

Associate Software Engineer at Virtusa