Android Design Patterns: The Singleton Pattern

Android Design Patterns: The Singleton Pattern

What Is the Singleton Pattern?

The Singleton Pattern is a software design pattern that guarantees a class has one instance only and a global point of access to it is provided by that class. Anytime multiple classes or clients request for that class, they get the same instance of the class. This Singleton class may be responsible for instantiating itself, or you can delegate the object creation to a factory class.

Let’s use the example of a cell phone and its owner. A phone is typically owned by a single person, while a person can own many phones. Anytime one of these phones rings, the same owner picks it up.

Benefits of the Singleton Pattern

In a typical Android app, there are many objects for which we only need one global instance, whether you are using it directly or simply passing it to another class. Examples include caches, OkHttpClient, HttpLoggingInterceptor, Retrofit, Gson, SharedPreferences, the repository class, etc. If we were to instantiate more than one of these types of objects, we’d run into problems like incorrect app behaviour, resource overuse, and other confusing results.

Implementation

It’s quite easy to implement this pattern. The following code snippet shows how a Singleton is created.

public class Singleton {

 

  private static Singleton INSTANCE = null;

 

  // other instance variables can be here

   

  private Singleton() {};

 public static Singleton getInstance() {

    if (INSTANCE == null) {

      INSTANCE = new Singleton();

    }

    return(INSTANCE);

  }

// other instance methods can follow 

}

In the code above, we have a static variable INSTANCE to hold an instance of the class. We also made the constructor private because we want to enforce noninstantiability—the class can only instantiate itself. The method getInstance() guarantees that the class is instantiated if it has not been, and that it’s returned to the caller.

Example: Creating a Single Instance of Retrofit

Retrofit is a popular library to connect a REST web service by translating the API into Java interfaces. To learn more about it, check out my tutorial here on Envato Tuts+.

Continue to read the full article on Tutsplus.

SHARE ON