How to use Single Instance Class / Singleton class in Android / Java ?

The single instance classes are mostly used when you don’t know how to create a object of this class from some distant class or instead of allocating memory for the class, just create object once and use it till entire life of the application.

The Single Instance class, also called at Singleton class just creates objects only once in entire life cycle of the application hence name Singleton class.

$ vim SingleInstanceClass.java
public com.android.example;

public class SingleInstanceClass {
        // variable to save global instance of this class
        private static SingleInstanceClass instance = null;

        /* Default constructor*/
        private SingleInstanceClass () {
        }

        // this method when called first time, creates the object
        // for this class and assigns to "instance" and returns same
        // when called afterwords, it just returns the pre-allocated
        // instance for the entire life cycle of this app
        public static SingleInstanceClass getInstance() {
                if (instance == null) {
                        instance = new SingleInstanceClass ();
                }
                return instance;
        }

        public void functionInSingletonClass () {
                //body of your function
        }

}       

here, we have added the comments to understand what each object and function does.

Now, we will write another class which actually uses the this singleton class and also calls the function from this class.

$ vim Hello.java
package com.android.example;

import com.android.example.SingleInstanceClass;

public class Hello {
        private SingleInstanceClass instance = null;

        //constructor of this class
        private Hello () {
                //we will class another function from this same class
                //which creates the instance of single ton class
                //and calls its function
                functionInHello()
        }

        private void functionInHello() {
                //get the instance of Single ton class
                //since getInstance() is a static method
                //from SingleInstanceClass class we can just call
                //this directly from here.
                instance = SingleInstanceClass.getInstance();

                //here as now we have instance of singleton class
                //we can call the function from this calss.
                instance.functionInSingletonClass();
        }
}       

the above is a very simple class which allocates instance of single ton class and shows you how you can call the function from single ton class.

Although this post refers to Android, this same code also works for standard java programs with little modifications.

Leave a Comment