1

这些发布全局常量的方式中哪一种更好?谢谢!!!

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);
4

2 回答 2

1

遵循更常见的约定的东西是这样的:

public class MyAppConstants {
    public static final String C1 = "STRING1";
    public static final String C2 = "STRING2";
}

然后你可以像这样稍后引用它:

System.out.println(MyAppConstants.C1);

但是,如果我必须在您给出的两者之间进行选择,我想我会选择第一个,因为枚举具有误导性并且在功能上没有帮助并且不会使代码更清晰。

于 2013-08-11T07:12:22.850 回答
0

对于像我这样喜欢简短代码的粉丝,他们喜欢尽量减少代码中的字符数,如果你不想在常量名前加上“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;

这样做还有其他好处,例如创建所有活动都可以使用的方法,这通常是一种很好的做法。

于 2014-11-25T23:50:00.223 回答