A walkthrough of Java Singleton class
A singleton is a design pattern that allows the only single instance to be created in the memory.
In Java, a singleton design pattern lets us create only one instance of a class throughout the application and it ensures that a single instance present in memory(JVM).
Some rules are must be applied when we create a singleton class.
- A public static method to get the instance of the class from anywhere in the application.
- Private constructor to instantiate the object of the class.
- It must have a private static variable of the same class which is the only reference of the class.
Example -
output:
There are several more ways to perform modification in
- Eager initialization — We can create a new object at the time of declaring a variable.
private static Singleton instance = new Singleton();
2. Through static initialization block.
3. Lazy initialization — Object is created when getInstance() method is called.
You can find this code on GitHub https://github.com/arpitbhatt027/core-java-programs/blob/master/src/interview_programs/SingletonDemo.java