SharedPreferences 应该是单例吗?相互矛盾的答案

Should SharedPreferences be a singleton? Conflicting answers

SharedPreferences 应该是单例 class 吗?我从消息来源得到相互矛盾的答案。这篇博文告诉我应该将 SharedPreferencesManager class 作为单例

https://www.codexpedia.com/android/android-sharedpreferences-singleton-example/

public class SharePref {
    private static SharePref sharePref = new SharePref();
    private static SharedPreferences sharedPreferences;
    private static SharedPreferences.Editor editor;

    private static final String PLACE_OBJ = "place_obj";

    private SharePref() {} //prevent creating multiple instances by making the constructor private

    //The context passed into the getInstance should be application level context.
    public static SharePref getInstance(Context context) {
        if (sharedPreferences == null) {
            sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
            editor = sharedPreferences.edit();
        }
        return sharePref;
    }

    public void savePlaceObj(String placeObjStr) {
        editor.putString(PLACE_OBJ, placeObjStr);
        editor.commit();
    }

    public String getPlaceObj() {
        return sharedPreferences.getString(PLACE_OBJ, "");
    }


    .  .  .

这个 SO 回答说我不需要:

There is no need to increase shared global state via Singletons. Android already has solutions for global state management via SharedPreferences and Bundles. It is enough. You should eliminate global state as much as you can

这是哪个?

恕我直言,SharedPrefs 的单例是多余的,你每次想要访问时都必须传递正确的 Context,所以这个 class 也可以像这样收集静态方法(种类伪代码):

public static void savePlaceObj(Context ctx, String placeObjStr) {
    Editor editor = getEditor(ctx);
    editor.putString(PLACE_OBJ, placeObjStr);
    editor.commit();
}

public static final String getPlaceObj(Context ctx) {
    return getSharedPreferences(ctx).getString(PLACE_OBJ, "");
}

private static final SharedPreferences getSharedPreferences(Context ctx) {
    return ctx.getSharedPreferences(ctx.getPackageName(), Activity.MODE_PRIVATE);
}

private static SharedPreferences.Editor getEditor(Context ctx) {
    return getSharedPreferences(ctx).Editor();
}

事实上,当您将单例用于 SP 时,在某些时候会有使用 getInstance(null) 的诱惑,因为 "it was already initiated earlier for shure" - 即使您将启动放在扩展中,您也无法确定Applicationclass。至少使用注释 getInstance(@NonNull Context context)