How to Create a Singleton Class in Java by Example?
Singleton: Exactly one instance of a class. Define a class that has only one instance and provide a global point of access to it.
Create a class singleton is very important in real-time projects. The Singleton's purpose is to control object creation, limiting the number of objects to one only. If we are creating an object of a class, again and again, that will definitely increase the memory and finally, our application will get slow.
For Example: If we have a restriction that we can create only one instance of a database connection. In this case, we will create only one object of the database and used it everywhere.
Implementation of Singleton class:
Singleton.java
- package com.java.deepak.singleton;
- public class Singleton {
- private static Singleton instance;
- private Singleton() {}
- public synchronized static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- System.out.println("New Object Created...!!!");
- } else {
- System.out.println("Object Already in Memory...");
- }
- return instance;
- }
- }
- We will make constructor as private. So then we can not create an object outside of a class.
- Create a private method to create an object of a class. By using this method, we will create an object outside of class.
SingletonClient.java
- package com.java.deepak.singleton;
- public class SingletonClient {
- public static void main(String[] args) {
- Singleton s1 = Singleton.getInstance();
- Singleton s2 = Singleton.getInstance();
- }
- }

Join the conversation! Your thoughts help the community grow.