Singleton: Exactly one instance of a class. Define a class that has only one instance and provide a global point of access of it.
Create a class singleton is very important in real time project. The Singleton's purpose is to control object creation, limiting the number of objects to one only. If we are creating a 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 restriction that we can create only one instance of a database connection. In this case we will create only one object of database and used 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 than we can not create an object outside of a class.
- Create a private method to create a 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();
- }
- }
Here we are calling singleton class two times.
Output:
In output, we can see that when we call method first time then new object will create but when we call second time then existing object will return.