搜尋此網誌

2015年1月13日 星期二

【Java】全域常數???

ref:
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);
Method1的方法較好。

沒有留言: