1

if i need use a global class what is the best option and why?

public class Global {

    public static JSONObject GetJsonResquest(String url){
        ....
    };
}

and then call Global.GetJsonResquest(url) in my activity

OR

  public class Singleton {
    private static Singleton ourInstance = new Singleton();

    public static Singleton getInstance() {
        return ourInstance;
    }

    private Singleton() {
    }
    public JSONObject GetJsonResquest(String url){
      .....
    }
}

and then use via Singleton.getInstance().GetJsonResquest("Asd");

pedroooo
  • 563
  • 1
  • 4
  • 17
  • 4
    Possible duplicate of [Difference between static class and singleton pattern?](http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern) – HendraWD Oct 21 '16 at 02:48
  • But if i need use a constants variables... example TIME_DEFAULT = 4000 AND MORES... OR METHODS CalculateValue(int jjdsjd) what is the bes way? my question is for best practice when only need 1 function or 1 constant in the activity and dont need load all – pedroooo Oct 21 '16 at 02:55
  • in this code example isbetter case one, you dont need ANY instance of Global in order to convert the string into jsonObject – ΦXocę 웃 Пepeúpa ツ Oct 21 '16 at 03:11

1 Answers1

0

When I need a global static variable, I like to group them into a class like

public class MyConstants {
    public static final int TIMEOUT = 10000;
}

To use it, i can call it like

long tick = System.currentThreadMillis();
while((System.currentThreadMillis() - tick) < MyConstants.TIMEOUT){
    Thread.sleep(1000);
}

So that when I change the TIMEOUT value, I don't have to change other classes that calls it

For global static method, I use them like

public class Utility{
     public static boolean isStringValidJson(String jsonString){
         return false;   
     }
}

Same reason as above. When I change isStringValidJson, other classes that calls it don't change

I do use the singleton pattern but only when I override the Application class. However, I set the instance value in OnCreate instead. This means that if OnCreate was not called, getInstance will return null

public class MyApplication extends Application {

    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static synchronized MyApplication getInstance(){
        return instance;
    }
}
Short answer
  • 144
  • 7