Search

Java - Google 也愛用的參數列舉方式

2015-10-09 8:33 PM

因為工作有機會接觸到 Google 的原始碼

就順便學到這個建構方式

可以說是既方便又結構化

最大的優點就是傳遞此類參數時可以用型態防呆

又可以在寫入資料庫時輕鬆轉換為數值

程式碼範例
  1. public class ArticleType extends EnumBase {
  2. // 儲存參數
  3. private static Map MAP = new LinkedHashMap<>();
  4. // 建立參數
  5. private static final String _NORMAL = "normal";
  6. private static final String _ALWAYS_TOP = "always_top";
  7. private static final String _DELETED = "deleted";
  8. // 建立參數物件
  9. public static final ArticleType NORMAL = new ArticleType(_NORMAL);
  10. public static final ArticleType ALWAYS_TOP = new ArticleType(_ALWAYS_TOP);
  11. public static final ArticleType DELETED = new ArticleType(_DELETED);
  12. protected ArticleType(String value) {
  13. super(value);
  14. }
  15. // 取得所有參數物件
  16. public static List enums() throws IllegalArgumentException, IllegalAccessException{
  17. return enums(ArticleType.class);
  18. }
  19. // 利用參數值取出物件
  20. public static ArticleType fromValue(String value){
  21. return MAP.get(value);
  22. }
  23. // 取得 Map 物件
  24. @SuppressWarnings("unchecked")
  25. @Override
  26. protected Map getMap() {
  27. return (Map) MAP;
  28. }
  29. // 取得參數名稱
  30. public String getName(){
  31. switch( this.getValue() ){
  32. case _NORMAL:
  33. return "一般文章";
  34. case _ALWAYS_TOP:
  35. return "置頂文章";
  36. case _DELETED:
  37. return "已刪除文章";
  38. default:
  39. return "無此類型";
  40. }
  41. }
  42. }

以下是父類別的程式碼

  1. public abstract class EnumBase {
  2.  
  3. protected String value;
  4.  
  5. // 創建時順便放入 Map 中
  6. protected EnumBase(String value) {
  7. super();
  8. this.value = value;
  9. this.setMap(value);
  10. }
  11.  
  12. // 取得所有參數物件
  13. protected static List enums(Class clazz)
  14. throws IllegalArgumentException, IllegalAccessException{
  15. List list = new ArrayList();
  16. Field[] fields = clazz.getFields();
  17. for( Field field : fields ){
  18. if( field.getType() == clazz ){
  19. @SuppressWarnings("unchecked")
  20. T target = (T) field.get(clazz);
  21. list.add(target);
  22. }
  23. }
  24. return list;
  25. }
  26. // 將參數放入 Map 中
  27. public void setMap(String value){
  28. this.getMap().put(value, this);
  29. }
  30. // 取得參數值
  31. public String getValue(){
  32. return value;
  33. }
  34. public String toString(){
  35. return this.getValue();
  36. }
  37. // 取得參數名稱
  38. public abstract String getName();
  39. // 取得 Map
  40. protected abstract Map getMap();
  41. }
各項資料連結
Google

No comments:

Post a Comment