【发布时间】: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 的用户。你的问题没有对错之分。你只会找到固执己见的答案。