Singletons per Activity context
Tags: android, activity, singleton, context
Published: 2017-05-23 04:14:21

---
title: Singletons per Activity context
published: true
cover_image: https://s3-us-west-2.amazonaws.com/my-blogresources/my-shots/IMG_20150822_194505.jpg
description: Singletons design pattern
tags: android, activity, singleton, context
---

# Singletons
[Singleton Design Pattern](https://en.wikipedia.org/wiki/Singleton_pattern) is by far the most common design pattern and the first one that come across to anyone when think about Design Patterns. It's so commonly used that there are people who can write the pattern in their sleep. 


## Android Studio Default Template
```Java
class Test {
    private static final Test ourInstance = new Test();

    static Test getInstance() {
        return ourInstance;
    }

    private Test() {
    }
}
```

The below is the template that we generally use in our team. 

## Our Template

```Java

class Test {
    private static final Test ourInstance;

    static Test getInstance() {
        if(ourInstance == null){
            ourInstance = new Test();
        }
        return ourInstance;
    }

    private Test() {
    }
}

```

I faced a situation where I was required to create a Singleton per activity, or a Singleton class that holds an instance of Activity context. Usually when you try to declare objects like '*Activity*' or '*Context*' as a static field in any Java class, Android Studio warns about memory leak via static objects. 

```
Do not place Android context classes in static fields; this is a memory leak.
```

To avoid that memory leakage, 
1. Do not store context (That's obvious! isn't it). 

2. Use *WeakReference* to store the context. 

```Java
private final WeakReference<Activity> mActivityContextRef;

public static void newInstance(Activity activity) {
    if (ourInstance == null) {
        ourInstance = new Test(activity);
    }
}

private Test(Activity activity) {
    mActivityContextRef = new WeakReference<>(activity);
}

```

> **Some of the best articles on Weak References:**  
> 1. [Romain Guy's Article](http://www.curious-creature.com/2008/12/18/avoid-memory-leaks-on-android/)  
> 2. [Articles from Google Developers Experts-1](https://medium.com/google-developer-experts/finally-understanding-how-references-work-in-android-and-java-26a0d9c92f83)
>3. [Articles from Google Developers Experts-2](https://medium.com/google-developer-experts/weakreference-in-android-dd1e66b9be9d)


Back to the earlier scenario that I described, I had to create an **Singletons per Activity**. Combining with our singleton template with the concept of *WeakReference*, I came up with this.

```Java
public static void newInstance(Activity activity) {
        if (ourInstance == null) {
            ourInstance = new Test(activity);
        } else {
            if (activity.equals(ourInstance.mActivityContextRef.get())) {
                LogUtils.debug(TAG, "newInstance: Same Activity; No need to create new instance");
            } else {
                LogUtils.debug(TAG, "newInstance: New Activity; Create new instance");
                ourInstance = null;
                ourInstance = new Test(activity);
            }
        }
    }

    private Test(Activity activity) {
        mActivityContextRef = new WeakReference<>(activity);
    }
```

This solution helped us to solve the issue we were facing. 

I don't argue that this is perfect solution and in fact a  **Word of Caution** When I was talking to one of my senior colleagues regarding the above *Singleton per Activity*, he questioned me that **Why would anyone require an *Activity* context in a Singleton POJO class**. That got me thinking and I realized that the class in question was handling [too many responsiblities](https://8thlight.com/blog/uncle-bob/2014/05/08/SingleReponsibilityPrinciple.html) and refactored using **MVP** design pattern. I will write that in another post.