[英]Best practices in two class
如果我需要使用全球类什么是最好的选择,为什么?
public class Global {
public static JSONObject GetJsonResquest(String url){
....
};
}
然后在我的活动中调用Global.GetJsonResquest(url)
要么
public class Singleton {
private static Singleton ourInstance = new Singleton();
public static Singleton getInstance() {
return ourInstance;
}
private Singleton() {
}
public JSONObject GetJsonResquest(String url){
.....
}
}
然后使用通过Singleton.getInstance()。GetJsonResquest(“Asd”);
当我需要一个全局静态变量时,我喜欢将它们分组为类
public class MyConstants {
public static final int TIMEOUT = 10000;
}
要使用它,我可以称之为
long tick = System.currentThreadMillis();
while((System.currentThreadMillis() - tick) < MyConstants.TIMEOUT){
Thread.sleep(1000);
}
因此,当我更改TIMEOUT值时,我不必更改调用它的其他类
对于全局静态方法,我使用它们
public class Utility{
public static boolean isStringValidJson(String jsonString){
return false;
}
}
与上述相同的原因。 当我更改isStringValidJson时 ,调用它的其他类不会更改
我确实使用单例模式,但只有当我重写Application类时。 但是,我在OnCreate中设置了实例值。 这意味着如果未调用OnCreate ,则getInstance将返回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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.