I need a class which handles my SharedPreferences and I came up with 3 ways of doing it, however after some research it seems most of them are considered "anti-patterns".
Type 1
public final class MyPrefs {
private MyPrefs(){ throw new AssertionError(); }
public static void setFavoriteColor(Context context, String value){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putString("color_key", value).apply();
}
public static void setFavoriteAnimal(Context context, String value){
// ...
}
// ...
}
/* Usage */
MyPrefs.setFavoriteColor(this, "yellow");
// Reason why it might be considered "Bad"
// Class is not OO, just collection of static methods. "Utility Class"
Type 2
public class MyPrefs {
private SharedPreferences mPreferences;
private static volatile MyPrefs sInstance;
public static MyPrefs getInstance(Context context){
if(sInstance == null){
synchronized(MyPrefs.class){
if(sInstance == null){
sInstance = new MyPrefs(context);
}
}
}
return sInstance;
}
private MyPrefs(Context context){
mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setFavoriteColor(String value){
mPreferences.edit().putString("color_key", value).apply();
}
public void setFavoriteAnimal(Context context, String value){
// ...
}
// ...
}
/* Usage */
MyPrefs myPrefs = MyPrefs.getInstance(this);
myPrefs.setFavoriteColor("red");
// Reason why it might be considered "Bad"
// Singleton's are frowned upon especially
// in android because they can cause problems and unexpected bugs.
Type 3
public class MyPrefs {
SharedPreferences mPreferences;
public MyPrefs(Context context){
mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setFavoriteColor(String value){
mPreferences.edit().putString("color_key", value).apply();
}
public void setFavoriteAnimal(Context context, String value){
// ...
}
// ...
}
/* Usage */
MyPrefs myPrefs = new MyPrefs(this);
myPrefs.setFavoriteColor("green");
// Reason why it might be considered "Bad"
// Lots of boilerplate and must create object every
// time you want to save a preference.
Now my preference wrappers obviously don't consist of only 2 setters, they have lots of getters and setters which do some side processing before saving values, so having the preferences saved and processed within the main activity would cause for a lot of messy code and bugs.
Now which of these approaches will not have a negative impact on performance/cause unexpected bugs?