In this tutorial, we will learn about the singleton design pattern and how to apply it in Java with the help of examples.
The singleton pattern is one of the simplest design patterns. Sometimes we need to have only one instance of our class .
Here's an example.
class SingletonExample {
// private field that refers to the object
private static SingletonExample singleObject;
private SingletonExample() {
// constructor of the SingletonExample class
}
public static SingletonExample getInstance() {
// write code that allows us to create only one object
// access the object as per our need
}
}
In the above example,
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.
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.