【问题标题】:Should SharedPreferences be a singleton? Conflicting answers [closed]SharedPreferences 应该是单例吗?相互矛盾的答案[关闭]
【发布时间】:2020-02-21 11:10:30
【问题描述】:

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

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 答案说我不需要:

https://stackoverflow.com/a/19148391/11110509

没有必要通过单例增加共享全局状态。 Android 已经有了通过 SharedPreferences 和 Bundles 进行全局状态管理的解决方案。就够了。你应该尽可能地消除全局状态

这是什么?

【问题讨论】:

  • 这完全取决于 API 的用户。你的问题没有对错之分。你只会找到固执己见的答案。

标签: android sharedpreferences


【解决方案1】:

SharedPrefs 的 imho 单例是多余的,每次要访问时都必须传递正确的 Context,所以这个类也可以通过收集这样的静态方法(一种伪代码):

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) 的诱惑,因为“它已经为舒尔早先启动了” - 即使您将启动置于扩展中,您也不能是舒尔Application 班级。至少使用注解getInstance(@NonNull Context context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    相关资源
    最近更新 更多