参考
应用最广的模式-单例模式
封装
public class Preferences {
private static Preferences singleton = null;
private String FILL_NAME = "Preferences";
private SharedPreferences sp;
private Preferences() { }
public static Preferences getInstance() {
if (null == singleton) {
synchronized (Preferences.class) {
if (null == singleton) {
singleton = new Preferences();
}
}
}
return singleton;
}
public void init(Context context){
sp = context.getSharedPreferences(FILL_NAME, Context.MODE_PRIVATE);
}
public void put(String key, Object value) {
SharedPreferences.Editor edit = sp.edit();
if (value instanceof String) {
edit.putString(key, (String) value);
} else if (value instanceof Integer) {
edit.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
edit.putBoolean(key, (Boolean) value);
} else if (value instanceof Long) {
edit.putLong(key, (Long) value);
} else if (value instanceof Float) {
edit.putFloat(key, (Float) value);
}
edit.apply();
}
public Object get(@NonNull String key, @NonNull Object defaultValue) {
if (defaultValue instanceof String) {
return sp.getString(key, (String) defaultValue);
} else if (defaultValue instanceof Integer) {
return sp.getInt(key, (Integer) defaultValue);
} else if (defaultValue instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultValue);
} else if (defaultValue instanceof Long) {
return sp.getLong(key, (Long) defaultValue);
} else if (defaultValue instanceof Float) {
return sp.getFloat(key, (Float) defaultValue);
}
return null;
}
}
初始化
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Preferences.getInstance().init(this);
}
}