[英]In Java, what is the better way to use Enums? With static constants or with constructors and off-file constants? [on hold]
[英]What is the better way of publishing global constants in Java?
这些发布全局常数的方法中哪一种更好? 谢谢!!!
Method 1: final class with public static final fields
public final class CNST{
private CNST(){}
public static final String C1;
public static final String C2;
static{
C1="STRING1";
C2="STRING2";
}
}
//so I could call C1, C2 like:
//...some code...
//System.out.println(CNST.C1);
//System.out.println(CNST.C2);
Method 2: singleton with enum
public enum CNST{
INST;
public final String C1;
public final String C2;
CNST{
C1="STRING1";
C2="STRING2";
}
}
//so I could call C1, C2 like:
//...some code...
//System.out.println(CNST.INST.C1);
//System.out.println(CNST.INST.C2);
遵循更常见的约定将是这样的:
public class MyAppConstants {
public static final String C1 = "STRING1";
public static final String C2 = "STRING2";
}
然后您可以像下面这样引用它:
System.out.println(MyAppConstants.C1);
但是,如果我必须在两者之间做出选择,我想我会选择第一个,因为该枚举具有误导性,对功能没有帮助,也无法使代码更清晰。
对于像我这样简短代码的粉丝,他们希望尽量减少代码中的字符数,如果您不想在常量名称前加上类名“ MyGlobaConstants”,则可以创建一个基数活动类(例如MyBaseActivity),并从中扩展您的所有活动。 因此:
public abstract class MyBaseActivity extends Activity {
public static final String SOME_GLOBAL_STRING = "some string";
public static final int SOME_GLOBAL_INT = 360;
这样做还有其他好处,例如创建所有活动都可以使用的方法,这通常是一种好习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.