我正在使用这样的方法
private static <T> void setPreference(String key, T value)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Controller.getContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value.toString());
editor.commit();
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,它putString是多种put方法之一。我也想使用putBoolean和putInt。我的问题是我想支持特定的类型(我不想像我所做的那样将所有内容保存为字符串),并且我想尽可能减少代码重复。我习惯了C#,这种事情很简单,所以我觉得我缺少明显的东西。
您可以使用if (value instanceof Boolean) { editor.putBoolean(..); }。
但这并不完全是OO。你能做的就是将责任转移到值对象上:
public intarface ValueHolder<T> {
void putInEditor(String key, Editor editor);
T getValue();
}
public class StringValueHolder extends ValueHolder<String> {
private String value;
// constructor here to initialize the value
public putInEditor(String key, Editor editor) {
editor.putString(key, value);
}
public String getValue() {
return value;
}
}
public class BooleanValueHolder extends ValueHolder<Boolean> {
private Boolean value;
// constructor here to initialize the value
public putInEditor(String key, Editor editor) {
editor.putBoolean(key, value);
}
public Boolean getValue() {
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
我同意,它更冗长,所以如果您不想使事情复杂化,请坚持使用instanceof解决方案。