Java Creational Design Patterns – Singleton Pattern
Singleton Pattern is one of the Creational design pattern. The singleton pattern puts restriction on object creation process; it restricts the instantiation of a class to one object. If we are using Singleton pattern, no need to instantiate class object, its the responsibility of the class to provide the way to access its one and only one object.
If your application deals with below questions then Singleton Pattern could be your solution.
- If a class need to have only one instance
- The class needs to be centrally accessible.
- You need to control how the class instances are created
<Here are ALL other Java Design Patterns, explained in detail with examples>
Singleton Pattern by Example
This pattern can be implemented in two different ways
- Eager initialization: In this method object of class is created when it is loaded to the memory by JVM. It is done by assigning the reference an instance directly. This approach can be used when you know that cost of object creation is not too high.
- Lazy initialization: In this method, object is created only when it is needed. This approach prevent resource wastage. An implementation of getInstance() method is provided which return the instance.
We will see both the ways in our coding sample.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public final class MySingletonEager { private static final MySingletonEager INSTANCE = new MySingletonEager(); private MySingletonEager() { } public static MySingletonEager getInstance() { return INSTANCE; } public void display() { System.out.println("Singleton Eager Init"); } } |
As you can see above approach is Eager. The class instance is initialized on loading of class in JVM. Below is most popular Singleton Lazy Init
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public final class MySingletonLazy { private static volatile MySingletonLazy instance = null; private MySingletonLazy() { } public static MySingletonLazy getInstance() { if (instance == null) { synchronized (MySingletonLazy.class) { if (instance == null) { instance = new MySingletonLazy(); } } } return instance; } public void display() { System.out.println("Singleton Lazy Init"); } } |
In above code you can see, a getInstance method is provided which in turn has synchronized block. This block will make sure that only one thread is doing the instance creation and rest other will use the Only available single instance.
Running the example
Running example is straight forward.
1 2 3 4 5 6 7 8 9 10 |
public class SingletonDemo { public static void main(String[] args) { MySingletonLazy.getInstance().display(); MySingletonEager.getInstance().display(); } } |
Output
1 2 |
Singleton Lazy Init Singleton Eager Init |
Conclusion
Few people consider the singleton to be an anti-pattern in that it is frequently used in scenarios where it is not beneficial. But by far this is one of the most popular pattern being used and asked in lots of interview questions.
So basically if you –
- Hide the constructor of the class.
- Define a public static operation (getInstance()) that returns the sole instance of the class.
You create a Singleton Class. More over you can make your singleton class implement Cloneable , Serializable and make it clone and serialize resistant.
You can refer the code at our Github repository using link
Download Code
<Here are ALL Java Design Patterns, explained in detail with examples>
the OCP course material implies it is better to use an inner class to do the singleton initialization.
This way, you don’t need a synchronized block, and it only gets initialized when used.
The example they use looks like this:
public class Logger {
private Logger() {
// private constructor
}
public static class LoggerHolder {
public static Logger logger = new Logger();
}
public static Logger getInstance() {
return LoggerHolder.logger;
}
public void log(String s) {
// log implementation
System.err.println(s);
}
}