问题
Which one of these ways of publishing global constants is better? THANKS!!!
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);
回答1:
Something that follows more usual conventions would be like this:
public class MyAppConstants {
public static final String C1 = "STRING1";
public static final String C2 = "STRING2";
}
Then you can refer to it later like this:
System.out.println(MyAppConstants.C1);
But if I had to pick between the two you give I guess I would choose the first, because the enum is misleading and doesn't help functionally and doesn't make the code clearer.
回答2:
for fans of short'n'sweet code like me, who like to minimize number of characters in code, if you wanna not have the need to pre-pend the constant name with a class name like "MyGlobaConstants", you can create a base activity class, like MyBaseActivity, and extend all your activities from it. As such:
public abstract class MyBaseActivity extends Activity {
public static final String SOME_GLOBAL_STRING = "some string";
public static final int SOME_GLOBAL_INT = 360;
Doing this has other benefits as well, such as creating methods that all your activities can use, and is generally a good practice.
来源:https://stackoverflow.com/questions/18169614/what-is-the-better-way-of-publishing-global-constants-in-java