Android - Google对Singleton模式的矛盾 [英] Android - Google's Contradiction on Singleton Pattern

查看:374
本文介绍了Android - Google对Singleton模式的矛盾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关Android中的Singleton模式使用以及它在保留上下文方面的缺点。实际上,当我实现以下代码:

I've been reading a bit about Singleton pattern usage in Android and its disadvantages regarding to keeping the Context. In fact, when I implement the following code:

private static HttpManager sSingleton;
private Context mContext;

private HttpManager(Context context) {

    mContext = context;
}

public static synchronized HttpManager getInstance(Context context) {

    if (sSingleton == null) {
        sSingleton = new HttpManager(context);
    }

    return sSingleton;
}

Android Studio向我显示以下警告:

Android Studio shows me the following warning:


不要在静态字段中放置Android上下文类(静态引用HttpManager,其字段mContext指向Context);这是一个内存泄漏,也会中断即时运行。

Do not place Android context classes in static fields (static reference to HttpManager which has field mContext pointing to Context); this is a memory leak and also breaks Instant Run.

但是,我可以看到Singletons实现并推荐在Android的文档页面

However, I can see Singletons implemented and recommended in this page of Android's docs.


如果您的应用程序不断使用网络,可能最有效的方法是设置一个可以延长应用程序生命周期的RequestQueue实例。你可以通过各种方式实现。推荐的方法是实现封装了RequestQueue和其他Volley功能的单例类。

If your application makes constant use of the network, it's probably most efficient to set up a single instance of RequestQueue that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality.

由于Google与自己相矛盾,有人可以指导我并就此提出建议?

Since Google is contradicting itself, can someone guide me and advise me on this point?

推荐答案


由于Google与自己相矛盾

Since Google is contradicting itself

不,不是。

引用的Lint警告并不抱怨创建单身人士。它抱怨创建一个单引号,持有任意的上下文的引用,因为这可能类似于 Activity 。希望通过将 mContext = context 更改为 mContext = context.getApplicationContext(),您将摆脱该警告虽然这可能会影响即时运行,但我无法对此进行评论)。

The quoted Lint warning is not complaining about creating singletons. It is complaining about creating singletons holding a reference to an arbitrary Context, as that could be something like an Activity. Hopefully, by changing mContext = context to mContext = context.getApplicationContext(), you will get rid of that warning (though it is possible that this still breaks Instant Run — I cannot really comment on that).

创建单身人士是一件好事,只要你非常仔细地做到这一点,避免内存泄漏(例如,持有一个不确定的静态引用活动)。

Creating singletons is fine, so long as you do so very carefully, to avoid memory leaks (e.g., holding an indefinite static reference to an Activity).

这篇关于Android - Google对Singleton模式的矛盾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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