Singleton Class in Java – Most Effective Ways to Implement it!

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

What is the singleton class in Java? How this class is different from the normal class? How to implement a Java singleton class? If no then you are on the right page. Here, you will get all the details about this class with the help of examples.

So, what are you waiting for? Let’s start with the introduction.

What is a Singleton Class in Java?

In object-oriented programming, a singleton class is a class that can have just a single object. After the first time, if you create an object and access it with the help of the class, the new variables and methods will also point to that object. So, whatever changes you made in the first object it will make changes to all other objects because the memory between them is shared, or they access a single memory.

To execute a singleton class in Java, you should keep these points in mind:

  • You must make the constructor private.
  • Use a static method that has a return type of the object of this singleton class.

Let’s revise the fundamental concept of Classes and Objects in Java

How to Implement a Singleton Class in Java?

There are two ways to implement this class; let’s discuss them one by one:

Java Singleton Class implementation process

With getInstance() method

package com.DataFlair.SingletonClass;
class Singleton
  { 
    private static Singleton single_instance = null;
    public String str;
    private Singleton()
      {
     str = "Hello Readers!, Welcome to DataFlair's Tutorial of Java";
    }
    public static Singleton getInstance()
    {
     if (single_instance == null)
     single_instance = new Singleton();
     return single_instance;
    }
  }
 class getInstanceMethodDemo
  {
     public static void main(String args[])
     {
    Singleton text1 = Singleton.getInstance();
    Singleton text2 = Singleton.getInstance();
    //text in upper case
    System.out.println("In Upper Case : ");
    text1.str = (text1.str).toUpperCase();
    System.out.println("String from text1 is " + text1.str);
    //text in lower case
    System.out.println("In Lower Case : ");
    text2.str = (text2.str).toLowerCase();
    System.out.println("String from text1 is " + text2.str);
     }
  }

Output-get-instance-method

Learn 3 Types of Variables in Java with Examples

Explanation:

When we first call the getInstance() method in the Singleton class, it creates an object of the class with a name, the object single_instance and gets back to the variable. Since single_instance is static, it is thus changed from null to a different object. Next time, if we want to call the getInstance() method, since single_instance is not null, it returns to the variable, rather than by representing the Java singleton class again.

With a name as a class name method in Java

package com.DataFlair.SingletonClass;
class Singleton1
{
  // static variable single_instance of type Singleton1
  private static Singleton1 single_instance=null;
  public String str;
   private Singleton1()
   {
     str = "Welcome to DataFlair";
    }
  public static Singleton1 Singleton1()
  {
    if (single_instance == null)
    {
     single_instance = new Singleton1();
    }
   return single_instance;
   }
}
public class nameMethodSingleton {
public static void main(String args[])
   {
     Singleton1 text = Singleton1.Singleton1();
     Singleton1 text1 = Singleton1.Singleton1();
     //text in upper case
     text.str = (text.str).toUpperCase();
     System.out.println("String in Upper Case " + text.str);
     System.out.println("");
     //text in lower case
     text1.str = (text1.str).toLowerCase();
     System.out.println("String in Lower Case " + text1.str);

   }
}

Output-name-method-singleton

Explanation

First of all, in the Singleton class, when we call the Singleton() method, it creates an object of class Singleton with the name single_instance and returns it to the variable. Since single_instance is static, it changes from null to a different object. Single_instance is not null, so next time if we try to call the Singleton() method, it returned to the variable, instead of representing the Singleton class again.

Drawbacks of Singleton Classes

While singletons offer benefits, it’s important to consider potential drawbacks:

1. Testing Challenges: Singletons can make unit testing more complex. Because the singleton instance is global, it can be difficult to isolate and test the behavior of a class that relies on it. Techniques like dependency injection can help mitigate this issue.

2. Reduced Flexibility: Singletons can limit design flexibility. Since there’s only one instance, you cannot easily substitute different implementations. If your application architecture demands different configurations or behaviors, singletons might not be the ideal choice.

3. Dependency Issues: Singletons can introduce tight coupling between classes. A class that relies on a singleton becomes dependent on its implementation details. This can hinder code maintainability and reusability in the long run.

4. Memory management: Memory is not optimised as the singleton creates an object that is to be used until the application lasts. So in the future, if there is no need for that instance, then it is reserved for that object, hence causing memory wastage.

5. Reduced Flexibility: If, later on, the application demands more instances to be added, then using the Singleton class is not the right choice. To improve the configuration and behaviour of an application, it becomes harder to add instances.

Recommended Reading – Abstract Class in Java

Summary

With the help of the getInstance() method and a name that is a class name method, we can implement the singleton class in Java. This type of class contains only one object. Furthermore, if you have any queries, feel free to ask in the comments section.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

Your email address will not be published. Required fields are marked *