将应用程序类用作单例 [英] Use application class as singleton

查看:90
本文介绍了将应用程序类用作单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android中,我们通常必须使用 Context 类.当类或方法需要 Context 时,我们通常使用 Activites Services 作为此类参数.以下代码来自我找到的一个网站,但我不知道这是否是一种好习惯,是否可以使用此解决方案:

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;
    }
}

首先,我可以在此处使用单例模式.我的意思是每次我的某些应用程序代码在Android中执行时,系统都会创建一个进程,因此也存在一个我可以在其他类中使用的应用程序上下文.

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.

另一方面,使用它是错误的.通过这种模式,每个类(以及应该避免使用 Context 对象的pojo和singletons)都可以简单地获得对实际的 Context 的有效引用(我认为)不是 Context 对象背后的想法.

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?

推荐答案

@CommonsWare的答案很好...只是补充...

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

我认为这是一个不好的解决方案,因为它可能会导致内存泄漏.即使发生这种情况非常困难,也要使用静态引用. Context实例非常糟糕,因为由于该静态引用而导致 ActivityManagerService 销毁该Application实例时,它将不会被清除... -如下所述,它不会引起任何后果在这种情况下,内存泄漏.

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.

我不喜欢这种解决方案...直接使用Context比使用它更安全(例如getApplicationContext()).

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

obs .:它也违反了 Singleton Pattern ,因为它不限制类的实例化,并且不能确保只能有一个实例.相关...

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

这篇关于将应用程序类用作单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆