初始化逻辑(例如大量单例)应该在 OnCreate 还是 OnResume 中吗?

2024-03-03

假设我有一个带有通用定位控制器、电池控制器、AppSateController 等 inilizations 方法的单例...

这些是否应该在 onResume 中而不是 OnCreate 中,因为 OnCreate 在每次旋转、每次更改为前台时都会被调用,等等......?


我的建议通常是像平常一样直接实现单例。忽略 Android,只做正常的事情,如下所示:

class Singleton {
    static Singleton sInstance;

    static Singleton getInstance() {
        // NOTE, not thread safe!  Use a lock if
        // this will be called from outside the main thread.
        if (sInstance == null) {
            sInstance = new Singleton();
        }
        return sInstance;
    }
}

现在在需要时调用 Singleton.getInstance() 。您的单例将在此时被实例化,并且只要您的进程存在,就会继续被重用。这是一个很好的方法,因为它允许您的单例被延迟分配(仅在需要时),而不是为您可能立即不需要的东西做一堆前期工作,这会导致您的启动(从而响应用户)受苦。它还有助于保持代码整洁,有关单例及其管理的所有内容都位于其自己的位置,并且不依赖于正在运行的应用程序中的某些全局位置来初始化它。

另外,如果您的单例中需要上下文:

class Singleton {
    private final Context mContext;

    static Singleton sInstance;

    static Singleton getInstance(Context context) {
        // NOTE, not thread safe!  Use a lock if
        // this will be called from outside the main thread.
        if (sInstance == null) {
            sInstance = new Singleton(context);
        }
        return sInstance;
    }

    private Singleton(Context context) {
        // Be sure to use the application context, since this
        // object will remain around for the lifetime of the
        // application process.
        mContext = context.getApplicationContext();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

初始化逻辑(例如大量单例)应该在 OnCreate 还是 OnResume 中吗? 的相关文章

随机推荐