常量類、常量接口和枚舉

第一種使用接口:

  1. public interface Constants{

  2. public static final int AUDIT_STATUS_PASS = 1;

  3. public static final int AUDIT_STATUS_NOT_PASS = 2;

  4. }

第二種使用類:

  1. public class Constans{

  2. public static final int AUDIT_STATUS_PASS = 1;

  3. public static final int AUDIT_STATUS_NOT_PASS = 2;

  4. }

第三種使用枚舉:

  1. public enum Constants {

  2. AUDIT_STATUS_PASS(1),

  3. AUDIT_STATUS_NOT_PASS(2);

  4.  
  5. private int status;

  6.  
  7. private Constants(int status){

  8. this.setStatus(status);

  9. }

  10.  
  11. public int getStatus() {

  12. return status;

  13. }

  14.  
  15. public void setStatus(int status) {

  16. this.status = status;

  17. }

  18.  
  19. }

第一種和第二種是一樣的,第一種寫起來更方便,不用public static final,直接int AUDIT_STATUS_PASS = 1就行。第三種好在能把說明也寫在裏面,比如

  1. public enum Constants {

  2. AUDIT_STATUS_PASS(1,"通過"),

  3. AUDIT_STATUS_NOT_PASS(2,"退回");

  4.  
  5. private int status;

  6. private String desc;

  7.  
  8. private Constants(int status,String desc){

  9. this.setStatus(status);

  10. this.desc = desc;

  11. }

  12.  
  13. public int getStatus() {

  14. return status;

  15. }

  16.  
  17. public void setStatus(int status) {

  18. this.status = status;

  19. }

  20. ...

  21. }

建議使用枚舉。《Effective Java》中也是推薦使用枚舉代替int常量的。

枚舉當然是首選,另如果不用枚舉,在《Effective Java》一書中,作者建議使用一般類加私有構造方法的方式,至於爲什麼不用接口,那就要上升到語言哲學問題了。

  1. public class Constants {

  2. private Constants() {}

  3. public static final int AUDIT_STATUS_PASS = 1;

  4. public static final int AUDIT_STATUS_NOT_PASS = 2;

  5. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章