Singleton Design Pattern

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists. Creates an object with only one instance and global access. The most common uses control access to a database or some shared resource such as files. Additionally used for logging, driver objects, caching.
In some cases it’s not necessary to create separate objects for each client and that’s might cause performance loss. How do we ensure that a class has only one instance and that the instance is easily accessible? We can provide this by making the class itself responsible for following its instance.
Use the Singleton pattern when
• there should be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
• when the signleton instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
Implementation
Singleton implementation approaches that we gonna discuss in this article.
- Eager initialization singleton
- Statick block singleton
- Lazy initialization singleton
- Thread-safe initialization
Basically to design a Singleton class:
Create private constructor to restrict instantiation of the class from other classes.
Create public static method that returns the instance of the class.
public class Singeton {
private static final Singeton INSTANCE = new Singeton();
private Singeton() { }
public static Singeton getInstance() {
return INSTANCE;
}
}
The first example refers to eager initialization singleton. In eager initialization, the instance of Singleton Class is created at the time of class loading however, it has a disadvantage that instance is created even might not be using it by client application. We should avoid the instantiation until unless client calls the getInstance method. Also, there is no exception handling and not thread safe.
We able to use static block for exception handling. Static blocks are executed in order of source code and before constructor. It’s used to initialize static variables.
public class Singleton {
private static Singleton instance;
static {
try {
instance = new Singleton();
} catch (Exception e) {
}
}
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
Static block initialization implementation is similar to eager initialization, except that provides exception handling. In both implementations creates the instance before it’s being not used. (EagerInitializationSingleton, StaticBlockSignleton)
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
As seen above, lazy initialization also, object is created only if it is needed. This may prevent resource wastage. This example works fine in case of the single-threaded. When it comes to multithreaded systems the following implementation can be used.
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
In this implementation the method that we create instance is synchronized, it causes slow performance as multiple threads cannot access it simultaneously. Because every time an input enters a synchronization mode, it remove the locks while in the mod and it’s not allow the content to be entered even if an instance has been created or not.
To fix that we able to use double checked locking that we could by verifying if we need to create the object in the first place.
We also use volatile to prevent cache incoherence issues. The volatile keyword does not cache the value of the variable and always read the variable from the main memory.
public class Singleton {
private static volatile Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null)
synchronized (Singleton.class) {
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
Hope this article helped you to understand some details of Singleton design pattern.
References:
Design Patterns: Elements of Reusable Object-Oriented Software