The Singleton Design Pattern

Often in object-oriented programming, we run into situations where we need to have a single instance of an object that can be globally accessed from the whole application. For example, if we needed to use an HTTP client for our whole application, the most efficient approach would be to use a single one maintaining session information. In such cases, the singleton pattern is extremely useful.

In particular to Android, the Singleton can be referenced by all classes in your application, but one must be careful to tear-down the singleton when its no longer needed (for example when the application calls onDestroy()) because the Singleton’s life cycle is not managed by the system.

Why not just make a class with all methods being static? It turns out that this is bad for modularity (since we are forced to use THAT particular class in our code). Also since access is global, we must also worry about concurrency (that is, if the singleton is created at the same time from two independent threads, resulting in the creation of multiple singletons).

Let’s see how we can implement this in Java.

public class Singleton {
   private final Singleton instance = new Singleton();

   private Singleton(){
      //... implementation goes here
      }

   public Singleton getInstance(){
      return this.instance;
      }
}

This is thread-safe because the singleton is created as soon as the class is initialized, so we don’t need to worry that two different threads may try to create it. There is another approach, which allows the singleton to be loaded only when needed.


public class Singelton {

private Singleton(){

//... implementation goes here

}

private static class SingletonHolder {

   private final Singleton instance = new Singleton();

}

public static Singleton getInstance(){

   return SingletonHolder.instance;
}

}

This is also thread-safe because the Singleton (which is final) is created the very first time getInstance() is called. Note in both examples that the constructors are private, to prevent other classes from accessing them.

Advertisements
This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s