Use application class as singleton

2019-07-15 07:58发布

In Android we often have to use Context classes. When a class or method requires a Context we often use Activites or Services for such arguments. The following code is from a website I found but I do not know if this is good practice and if it is okay to use this solution:

public class MyApplication extends Application {
    private static MyApplication singleton;

    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
    }

    public static MyApplication getInstance() {
        return singleton;
    }
}

In first place it looks okay to me to use a singleton pattern here. I mean every time some of my app code is executed in Android the system creates a process and therefore also an application context exists which I can use in other classes.

On the other hand it fells wrong to use this. With this pattern every class (also pojo and singletons where we should avoid a Context object) are able to simply get a valid reference to the actual Context which (I think) is not the idea behind the Context object.

So what do you think about this solution? Is it okay to use it or are there some reasons (e.g. lifecycle of application, etc.) to avoid this? Or are some assumptions from me here wrong?

2条回答
Bombasti
2楼-- · 2019-07-15 08:02

Yes, you are correct. It is possible to design the application in such a way that we don't need this Application class Instance.

I use Dependency Injection pattern in my project. Say, for instance, my Presenter class needs a DataRepository class instance to fetch the data. And the DataRepository class needs a Context to access Database or SharedPreferences.

It is possible to create the DataRepository class inside my Presenter class using the Application instance. But using Dependency Injection pattern, I create the DataRepository outside of the Presenter (possibly Fragment/ Activity) and the pass the DataRepository instance to the Presenter via its constructor.

查看更多
做自己的国王
3楼-- · 2019-07-15 08:19

Very good @CommonsWare's answer... just complementing...

I believe it is a bad solution because it can cause a Memory Leak... Even though it is very very difficult to happen it... to use a static reference to a Context instance is very bad because this Application instance will not be cleaned when ActivityManagerService destroys it due to that static reference... -- As commented below, it cannot cause any memory leak in this case.

I don't like this kind of solution... it's safer to use the Context directly than it (e.g. getApplicationContext()).

obs.: It is also Violating Singleton Pattern because it is not restricting the instantiation of the class and doesn't ensure that there can be only one instance of it... but it is not relevant...

查看更多
登录 后发表回答