Singleton Pattern In Android

In this blog, I am describing the most important concept of Android Development which is the Singleton Pattern. It is also a very important interview question that is asked to Android Developers.  
 

What is Singleton in Android?

 
It is basically a design pattern we use in Android Application Development. 
 

How it is achieved?

 
It is achieved by simply making the constructor of a class as private.

 
Purpose of this pattern?

 
This pattern is basically used to restrict a class of making new instances. We use this pattern when we want a class to not be able to create a new instance in any way.
 
Making a singleton is not difficult but making it perfect is a thing that is a little challenging.  
 
Below is the example of a perfect singleton.
  1. pubic class SingletonClass{  
  2.    private static SingletonClass sClassInstance;  
  3.    private SingletonClass(){  
  4.       if(sClassInstance != null){  
  5.          throw new RuntimeException("getInstance() method will be used to get single instance of this class");  
  6.       }  
  7.    }  
  8.    public synchronized static SingletonClass getInstance(){  
  9.       if(sClassInstance == null){  
  10.          sClassInstance = new SingletonClass();  
  11.       }  
  12.    return sClassInstance;  
  13.    }  
  14. }  
In this examle, a class is defined and named as SingletonClass, which is basically a singleton class. This class contains a private static instance of class, a private constructor, and a synchronized static method getInstance(). 
 

Why do we use synchronized?

 
It is necessary to use while working in a multithreaded environment. It prevents two threads creating NEW INSTANCE for each. There may be a time when two threads access the method at the same time and if we will not use synchronized Singleton pattern, the rule will break and a new instance will be created in the heap which is an extra load and nothing else. To avoid this, it is necessary to use synchronized with an instance method.
Ebook Download
View all
Learn
View all