java - Android——谷歌对单例模式的矛盾

标签 java android design-patterns singleton

我一直在阅读一些关于 Android 中单例模式的使用及其在保持上下文方面的缺点。事实上,当我实现下面的代码时:

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 向我显示以下警告:

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 已实现并被推荐 in this page of Android's docs .

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.

由于谷歌自相矛盾,有人可以在这一点上指导我并给我建议吗?

最佳答案

Since Google is contradicting itself

不,不是。

引用的 Lint 警告并不是在提示创建单例。它提示创建持有对任意 Context 的引用的单例,因为这可能类似于 Activity。希望通过将 mContext = context 更改为 mContext = context.getApplicationContext(),您将摆脱该警告(尽管这可能仍然会破坏 Instant Run — 我无法对此发表评论)。

创建单例是可以的,只要您非常小心地这样做,以避免内存泄漏(例如,持有对 Activity 的无限期 static 引用)。

关于java - Android——谷歌对单例模式的矛盾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39840818/

相关文章:

c++ - 同步来自多个对象的异步调用

java - 纹理渲染不正确(OpenGL)

java - 在java中获取文件路径

ClientService 的 Android 异步任务错误

android - DialogFragment如何影响调用activity的生命周期

java - 单例是有状态的吗?

java - 在 Eclipse 中复制包

java - 更改 wsimport 绑定(bind)文件以指向本地资源

android - 如何在ViewModel中获取上下文

vb.net - 枚举类型实现位于类实现内部还是外部