工具类--常量类
?共有四種方式:
1 /** 2 * Method One 3 * 定義接口類,采用接口(Interface)的中變量默認為static final的特性。 4 */ 5 interface ConstantInterface { 6 String SUNDAY = "SUNDAY"; 7 String MONDAY = "MONDAY"; 8 String TUESDAY = "TUESDAY"; 9 String WEDNESDAY = "WEDNESDAY"; 10 String THURSDAY = "THURSDAY"; 11 String FRIDAY = "FRIDAY"; 12 String SATURDAY = "SATURDAY"; 13 } 14 /** 15 * Method Two 16 * 定義枚舉 17 */ 18 enum ConstantEnum { 19 SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 20 } 21 /** 22 * Method Three 23 * 定義常量類 24 */ 25 class ConstantClassField { 26 public static final String SUNDAY = "SUNDAY"; 27 public static final String MONDAY = "MONDAY"; 28 public static final String TUESDAY = "TUESDAY"; 29 public static final String WEDNESDAY = "WEDNESDAY"; 30 public static final String THURSDAY = "THURSDAY"; 31 public static final String FRIDAY = "FRIDAY"; 32 public static final String SATURDAY = "SATURDAY"; 33 } 34 /** 35 * Method Four 36 * 定義bean 37 */ 38 class ConstantClassFunction { 39 private static final String SUNDAY = "SUNDAY"; 40 private static final String MONDAY = "MONDAY"; 41 private static final String TUESDAY = "TUESDAY"; 42 private static final String WEDNESDAY = "WEDNESDAY"; 43 private static final String THURSDAY = "THURSDAY"; 44 private static final String FRIDAY = "FRIDAY"; 45 private static final String SATURDAY = "SATURDAY"; 46 public static String getSunday() { 47 return SUNDAY; 48 } 49 public static String getMonday() { 50 return MONDAY; 51 } 52 public static String getTuesday() { 53 return TUESDAY; 54 } 55 public static String getWednesday() { 56 return WEDNESDAY; 57 } 58 public static String getThursday() { 59 return THURSDAY; 60 } 61 public static String getFirday() { 62 return FRIDAY; 63 } 64 public static String getSaturday() { 65 return SATURDAY; 66 } 67 } 68 69 /** 70 * 測試代碼 71 * */ 72 class TestConstant { 73 static final String day = "saturday"; 74 public static void main(String[] args) { 75 System.out.println("Is today Saturday?"); 76 System.out.println(day.equalsIgnoreCase(ConstantInterface.SATURDAY)); 77 System.out.println(day.equalsIgnoreCase(ConstantEnum.SATURDAY.name())); 78 System.out.println(day.equalsIgnoreCase(ConstantClassField.SATURDAY)); 79 System.out.println(day.equalsIgnoreCase(ConstantClassFunction.getSaturday())); 80 } 81 }方法一采用接口(Interface)的中變量默認為static final的特性。
方法二采用了Java?5.0中引入的Enum(枚舉)類型。
方法三采用了在普通類中使用static final修飾變量的方法。
方法四類似方法三,但是通過函數來獲取常量,類似bean,也就是有自帶的get方法。
?
使用常量類原因:
定義全局變量會增加程序耦合成都。最佳的方法是避免定義全局變量。如果是參數等,可以寫入配置文件,否則方法二是最為推薦。方法三是比較直觀。方法一和方法三本質上一樣。方法四提供了靈活性。
轉載于:https://www.cnblogs.com/silence-fire/p/6825022.html
總結
- 上一篇: Entity Framework 的小实
- 下一篇: mysql语句优化方案(网上流传)