Use application class as singleton

做~自己de王妃 提交于 2019-12-11 01:40:56

问题


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?


回答1:


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...




回答2:


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.



来源:https://stackoverflow.com/questions/45402302/use-application-class-as-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!