This is one of the best-known patterns and is perhaps the first that comes to mind when you ask us about design patterns in Java.
The goal is to have only one instance of a class involved and ensure that this happens every time this instance is needed.
The Singleton design pattern has many ways of being implemented but we will see here the basis of its implementation consisting of:
- Create a private constructor avoiding the possibility of using new
- Create a static variable in the class that will save the instance of that class.
- Create a public method that will always return the same instance of the class we have saved in the variable.
What is a Singleton design pattern
Normally when we create an object in Java we use the keyword new.
This creates a new Object whenever required. However, there are times when we do not want to create a new object, on the contrary, we want to ‘share’ the object.
The singleton design pattern ensures that only one object is created and that only one instance of the object exists for the class.
Every time we need the object we will get the same instance.
How to implement the Singleton pattern
There are several ways to implement the Singleton pattern. Let’s look at each.
Basic Singleton Pattern Implementation
This is the basic form a Singleton class would have. We make the constructor private to avoid its creation with new, and we define a method that always returns the same instance.
package patterns;
public class SingletonExample {
private static SingletonExample instance = new SingletonExample();
private SingletonExample() {
}
static SingletonExample getInstance() {
return instance;
}
}
Singleton Lazy Implementation
If we see the previous implementation we can think that we are creating an instance always, instance = new SingletonExample(), even if it is not required. We can think of another implementation where the object is created when required.
For this, the variable remains null and we initialize it the first time the method getInstance() is invoked.
To prevent two threads from entering simultaneously the first time we synchronize the instance creation.
package patterns;
public class SingletonExample2 {
private static SingletonExample2 instance;
private SingletonExample2() {
}
static SingletonExample2 getInstance() {
if (instance == null) {
synchronized (SingletonExample2.class) {
if (instance == null) {
instance = new SingletonExample2();
}
}
}
return instance;
}
}
In this article, you learn the two simplest ways to create a Singleton class.
You can review this code GitHub