jeudi 14 septembre 2017

Why to check singleton instance if null?

I wrote this kind of class before I see singleton design pattern;

public class Settings {
    public static Boolean prop1;
    public static Boolean prop2;
    public static Boolean prop3;

    public static Settings newInstance(Context c) {
        Settings settings = new Settings();
        setValues();
        return settings;
    }

    //just as an example
    static void setValues(){
    prop1 = pro2= prop3 = true;
    }
}

Note; I run newInstance() function once, and I don't use object returned from newInstance (Sounds like it could be void too), and I directly use/edit properties of settings like Boolean x = Settings.prop1; or Settings.prop1 =false; all across app. (I'm aware of consistency, but this is what I need)

Besides synchronization and thread safety, why everybody is saying that It should be initialized like following, and Settings.instance or Settings.getInstance().prop1 should be accessed instead of Settings.prop1;

public static Settings getInstance(){
   if(settings=null){
      settings=new Settings();
   }
   return settings;
} 

Aucun commentaire:

Enregistrer un commentaire