How to Create Singleton Class in Java
In Java, Singleton class is a class that controls the object creation. It means the singleton class allows us to create a single object of the class, at a time. It is usually used to control access to resources, such as database connections or sockets. It ensures that only one connection is made and a thread can access the connection at a time.
Nevertheless, if we try to create the second object of the singleton class, it points to the first instance of the singleton class. In this section, we will learn how to create Singleton class in Java.
To create a singleton class, we must follow the steps, given below:
The example of singleton classes is Runtime class, Action Servlet, Service Locator. Private constructors and factory methods are also an example of the singleton class.
By using the class name if we are calling a method and that method returns the same class object such type of method is called a factory method. For example:
The above method returns an object of that class's type.
Difference Between Singleton Class and Normal Class
The main difference between these two classes is an instantiation. To create an instance of a normal class, we use a constructor. On the other hand, to create an instance of a singleton class, we use getInstance() method.
Generally, we use the class name as the method name. It avoids confusion.
Example of Singleton Class
Let's create a singleton class.
Let's create the main class with the name Test.
IT IS AN EXAMPLE OF SINGLETON CLASS. IT IS AN EXAMPLE OF SINGLETON CLASS. IT IS AN EXAMPLE OF SINGLETON CLASS.
Have you noticed the concept of instantiation in the SingletonClassExample class? No, let's understand the working. Whenever we call getInstance() method, the first time, it creates an object of the class with the name s and returns it the variable. The variable s changed from null to some object because it is a static variable. The second time when we call the getInstance() method it returns the same variable s, instead of creating the new one object.
In the main class Test, we have created three instances (a, b, and c) of the Singleton class by invoking the getInstance() method. Here, a point should be noted that objects b and c are not formed in real, instead, both objects point to the previously created object i.e. a.
Another point to be noted that if we perform any modification to the object (such as variables) a, it also reflects the objects b and c. On the other hand, if we change the variable of object c, it also reflects changes in other objects.