Singleton Explained

Basics

Normal java classes can be instantiated as many times as you like. The instances don't know anything about each others. Singleton works different way. It is a class that can be instantiated only once. When any other code calls singleton, it always uses the same instance with same data and same methods. So the data and methods in singleton are shared between everybody who wants to use them.

You can code your app without any singletons but they may be useful in some cases:

  • To control concurrent access to a shared resource.
  • When logging data.
  • When you need global variable, etc.

Create singleton

The easiest way to create singleton is to use Android Studio 3+ new file feature. Select from menu File/New/Singleton and give it a new name. You get a very simple singleton class, such as below.

SingletonClass.java
package com.example.singleton;

class SingletonClass {
    private static final SingletonClass ourInstance = new SingletonClass();

    static SingletonClass getInstance() {
        return ourInstance;
    }

    private SingletonClass() {}

    // Put your methods here

}

Singleton Anatomy

Line 1 is a package declaration.

In line 3 we declare the class named SingletonClass.

Line 4 creates a new instance of the SingletonClass if it doesn't exist yet.

Line 6 has method getInstance that returns the same ourInstance every time when we call singletonClass.

Line 10 is the class constructor. Because it is private, it cannot create new instances.

Calling Singleton

You can call the singleton this way:

MainActivity.java
.
.
SingletonClass.getInstance.methodName();
.

This type of singleton is suitable for almost all apps, unless you do something very special.