DEV Community

Cover image for What are Singleton classes and Why do we need them?
Tanmoy Sarkar
Tanmoy Sarkar

Posted on

What are Singleton classes and Why do we need them?

What is Singleton Class?

While doing projects, we sometimes want to keep only one instance of a class and don't want to pass the instance of an object by argument in each function.


class ClassA {
      // sample codes
}

object1 = ClassA();
object2 = ClassA();
object3 = ClassA();
Enter fullscreen mode Exit fullscreen mode

In the above example, we want that when we call the ClassA constructor, every time it returns the same instance of an object in memory instead of creating a new thing every time the constructor is called.

When do we need Singleton Class?

Let's discuss the real-life use of singleton class.

  • API Client : During website / android / ios / native application development, we usually need to design an API client to establish communication between our app and server. 90% of the time, the API request is protected by some sort of authentication mechanism.

    If we create an instance of an API client for sending each API request, we need to configure the client with authentication details (JWT Key, API Key, Bearer Token, etc.).

    But we don't want to do this thing again and again for each request. Here we can use the concept of Singleton Class and resolve the issue.

  • Database Client : Like the issues for API Client, in the case of database client we have a limit on creating instances of objects of particular database clients. So we need to use only a single instance of Database Client / ORM Client in the whole project.

What is the concept behind Singleton Class?

In every programming language, we get a special type of variable static for class, which helps to keep only a single instance of the variable in all object instances of that particular class.

Let's get started learning this

  • Let's define a dummy class

    class ExampleA{
      // Class variable
      int counter = 0;
      // Special function to create/get object of instance
      static ExampleA getInstance(){
      }
    }
    
  • We need to create a static variable which will store instances of objects of their own class.

    class ExampleA{
      // Static variable
      static ExampleA instance;
      // Class variable
      int counter = 0;   
      // Special function to create/get object of instance
      static ExampleA getInstance(){
      }
    }
    
  • But we don't want to create an instance of an object if it does not need anywhere in our program.

      // Static variable
      static ExampleA instance = null;
    
  • Now, we came to the main part, designing the getInstance static function. In this function, we will return the instance of already existing object. If no object currently available, we will create

Kindly see the comments of the code to understand

class ExampleA{
  // Static variable
  static ExampleA instance = null;
  // Class variable
  int counter = 0;
  // Special function to create/get the object of instance
  static ExampleA getInstance(){
    // If no instance has already created, create a new one and assign it to an instance variable 
    if(instance == null) instance = ExampleA();
    return instance;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • That's All 🎉🎉

Let's implement the logic in Java & Run

Code -

class ExampleA{
    static ExampleA instance;
    int counter = 0;

    public static ExampleA getInstance(){
        if(instance == null){
            instance = new ExampleA();
        }
        return instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

Write little bit driver code to test -

public class testProgram {
    public static void main(String[] args) {
        ExampleA object1 = ExampleA.getInstance();
        object1.counter++;

        ExampleA object2 = ExampleA.getInstance();
        object2.counter++;

        System.out.println(object2.counter);
    }    
}
Enter fullscreen mode Exit fullscreen mode

Let's run the program By object1.counter++, the counter goes from 0 to 1. As the object2 is the same instance, by object2.counter++, the counter goes from 1 to 2.

Output -

2
Enter fullscreen mode Exit fullscreen mode

🏊🏊 Nice, our output comes perfect, which means now in the program, where I want the object, I can simply call ExampleA.getInstance(), and access the function and values of the object.

Best Practice

If the language has concept of public and private methods of class, make sure to make the default constructor to private.

What's your task?

If you leave this after understanding, you gonna face issues..Better write a Singleton Class in your favourite language and post it in a comment for a reference for others.

Thank You 👼👼

Any issue, comment down

Top comments (2)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Hi, just a small note: Classes are not the ones that are "single". A Singleton is a single object, not a single class.

Collapse
 
tanmoysrt profile image
Tanmoy Sarkar

Thanks for feedback. I will refactor that.