JAVA常量類的實現方式

前言

衆所周知,系統裏有不少好比訂單狀態、審覈狀態;性別、結算方式、交易類型等屬性,這些屬性只有幾個值,通常用0、一、二、3等的數字標識存入數據庫,每次對這些屬性所屬對象的增刪改操做,都會在代碼裏給狀態設置值,因爲項目是多人開發的,若是每次設置值的時候都直接set 0、一、2,容易出錯,並且狀態假設不用0、一、2表示了,用一、二、3表示,這時候全部set狀態的地方都得改變,維護麻煩。因此用常量表示狀態值,甚好。html

據我目前所知,系統裏實現常量的方式有三種:java

1,  接口常量數據庫

2,  類常量express

3,  枚舉後端

一:接口常量

Java程序裏實現常量,jdk1.5以前,沒有枚舉類,有的用的接口來實現系統中的常量:架構

如java的swing裏有一個SwingConstant:app

複製代碼
public interface SwingConstants {

        /** 
         * The central position in an area. Used for
         * both compass-direction constants (NORTH, etc.)
         * and box-orientation constants (TOP, etc.).
         */
        public static final int CENTER  = 0;

        // 
        // Box-orientation constant used to specify locations in a box.
        //
        /** 
         * Box-orientation constant used to specify the top of a box.
         */
        public static final int TOP     = 1;
        /** 
         * Box-orientation constant used to specify the left side of a box.
         */
        public static final int LEFT    = 2;
       
       //。。。省略其餘代碼
   }
複製代碼

接口常量,寫起來方便,看着簡潔,可是爲了讓其餘人知道每一個常量的含義,必須寫註釋,若是須要在用到常量對應的信息時候,須要看着註釋來寫。前後端分離

如:在其餘地方須要用到 SwingConstants.CENTER 的含義,必須看類裏的註釋,知道他表示中心。若是常量不少的話,把全部的常量都放在這一個接口裏邊,這種方式感受也不是很友好。dom

申哥,瑞友的架構師,個人老鄉、偶像)看了申哥之前的項目,發現一個常量類,也是接口常量類,在接口裏定義靜態內部類,可是比上邊這種要好,他能夠把不一樣的功能的常量類進一步分類,看代碼:jsp

複製代碼
public interface UtilConstants {
    /**
     * 
     * 公共常量
     *
     */
    public static class Public {
        public static final String ID = "TESTID";
    }
    
    /**
     * JSP路徑
     */
    public static class JspFilePath {
        public static final String TESTCONTROLLER = "jsp/basic/"; 
        public static final String TEMPLATE_PAGEPATH = "basic/template/"; // 模板(測試)
    }
    
    /**
     * vo 對象的一些公共的屬性名稱 
     *
     */
    public static class VoFields {
        public static final String ACTIONTIME = "operateTime";//操做時間
        public static final String ACTIONUSERNAME = "operatorName";//操做人姓名
        public static final String CHECKTIME = "auditTime";//審覈時間
        public static final String CHECKUSERID = "checkUserId";//審覈人ID
        public static final String CHECKUSERNAME = "auditPerson";//審覈人姓名
        public static final String CREATETIME = "createTime";        // 建立時間
        public static final String CREATEUSERID = "createUserId";// 建立人code
        public static final String INSERTUSERNAME = "createUserName";// 建立人姓名
        public static final String UPDATETIME = "updateTime";        // 修改時間
        public static final String UPDATEUSERID = "updateUserId";// 修改人CODE
        public static final String UPDATEUSERNAME = "updateUserName";// 修改人姓名
        public static final String DELFLAG = "delFlag";             // 刪除標記
        public static final String DBID = "dbid";                    // 主鍵
    }
    
    
    
}
複製代碼

使用,把不一樣功能的常量放在了接口的內部類裏,經過不一樣的內部類,調用的時候能夠更明確好找吧。

UtilConstants.JspFilePath.TEMPLATE_PAGEPATH
UtilConstants.VoFields.CHECKTIME

二:類常量

目前中彩網的項目是這樣作的,還有過完年去待過4天的蛋疼學院的代碼,也是這麼作的,雖然有了枚舉,多是因爲設計者習慣問題,還有不少人用的類常量,

定義了類常量,用一個Map<Integer, String>來封裝常量對應的信息,在static代碼塊裏,類初始化的時候執行一次put。用的時候

ResponseCode.RESP_INFO.get("DATABASE_EXCEPTION");就能取出響應信息

因爲項目是先後端分離,在接口文檔裏須要寫上狀態碼,還得寫上狀態碼對應的提示信息,並且咱們的響應類 RespInfo 有message屬性,就是保存常量類裏狀態碼對應的信息的。

代碼:

複製代碼
public class ResponseCode {

    /** 系統處理正常 */
    public static final int SUCCESS_HEAD = 0;

    /** 系統處理未知異常 */
    public static final int EXCEPTION_HEAD = 1;

    /** JSON解析錯誤 */
    public static final int JSON_RESOLVE = 2;

    /** 類型不匹配 */
    public static final int TRANSTYPE_NO = 3;

    /** Head - messageID未賦值 */
    public static final int HEAD_messageID = 4;

    /** Head - timeStamp未賦值 */
    public static final int HEAD_timeStamp = 5;

    /** Head - messengerID未賦值 */
    public static final int HEAD_messengerID = 6;

    /** Head - transactionType 未賦值 */
    public static final int HEAD_transactionType = 7;

    /** digest校驗不經過 */
    public static final int HEAD_DIGEST = 8;
    
    /** src校驗不經過 */
    public static final int HEAD_SRC_NULL = 10;
    
    /** 協議包含非法字符 */
    public static final int ILLEGAL_MESSAGE = 11;

    /** 數據庫異常 */
    public static final int DATABASE_EXCEPTION = 9;
    public static final Map<Integer, String> RESP_INFO = new HashMap<Integer, String>();

    static {
        // Head 相關
        RESP_INFO.put(SUCCESS_HEAD, "系統處理正常");
        RESP_INFO.put(EXCEPTION_HEAD, "系統處理未知異常");
        RESP_INFO.put(JSON_RESOLVE, "JSON解析錯誤");
        RESP_INFO.put(TRANSTYPE_NO, "類型不匹配");
        RESP_INFO.put(HEAD_messageID, "messageID未賦值");
        RESP_INFO.put(HEAD_timeStamp, "timeStamp未賦值");
        RESP_INFO.put(HEAD_messengerID, "messengerID未賦值");
        RESP_INFO.put(HEAD_transactionType, "transactionType未賦值");
        RESP_INFO.put(HEAD_DIGEST, "digest校驗不經過");
        RESP_INFO.put(DATABASE_EXCEPTION, "數據庫異常");
        RESP_INFO.put(HEAD_SRC_NULL, "src未賦值");
        RESP_INFO.put(ILLEGAL_MESSAGE, "協議包含非法字符");
        
    }
}
複製代碼

這種類常量比接口常量好,由於能夠定義狀態碼對應的提示信息。

三:枚舉

全部的枚舉類都是Enum類的子類,就行Object類同樣,只是沒有寫出來,因此能夠枚舉類可調用Enum的方法。注意是逗號分隔屬性,只有屬性後邊沒有方法的話,最後加不加分號都行

代碼:

public enum Season {
    SPRING,SUMMER,AUTUMN ,WINTER
}

使用:能夠直接使用屬性,也能夠調用Enum的方法如values方法

System.out.println(Season.AUTUMN);
        System.out.println(Season.values());
        Season[] values = Season.values();
        System.out.println(values[0]);

能夠在枚舉類中添加一些構造器、方法和域:

私有化構造器,構造器只是在構造枚舉常量的時候被調用如SMALL(「S」)

複製代碼
/**
 * 衣服尺寸
 */
public enum Size {

    SMALL("S"),
    MEDIUM("M"),
    LARGE("L"),
    EXTRA_LARGE("XL");
    
    /**
     * 縮寫
     */
    private String suoxie;
    
    private Size(String suoxie){
        this.suoxie = suoxie;
    }
    
    public String getSuoxie(){
        return suoxie;
    }
    
    
    
    public static void main(String[] args) {
        //1:toString()方法返回常量的名 
        System.out.println(Size.SMALL.toString());//SMALL
        
        //2:valueOf()
        System.out.println(Size.valueOf("LARGE"));
        
        //3:values:返回每一個常量名
        //SMALL MEDIUM LARGE EXTRA_LARGE
        Size[] sizes = Size.values();
        /*for (Size size : sizes) {
            System.out.println(size);
        }*/
        
        //4:ordinal 返回常量的位置,從0開始
        System.out.println(Size.LARGE.ordinal());
        
        int i = Size.EXTRA_LARGE.compareTo(Size.EXTRA_LARGE);
        System.out.println(i);

System.out.println(Size.LARGE.getSuoxie());
    }
}
複製代碼

申哥的枚舉:

實際項目中不會每一個類型都弄一個枚舉類,假設那樣,系統中會有不少枚舉類,每一個類裏邊只有幾個屬性,那樣類太多,感受不必,因此申哥設計了一個常量類Constants,在常量類裏定義了多個靜態枚舉類,這個和上邊說的申哥在接口常量裏定義靜態內部類有點相似,不過如今換成了枚舉。

接口裏定義靜態內部類好處:對不一樣功能的常量進行分類,用起來比較明確,可是因爲是interface,裏邊不能定義static靜態代碼塊,因此沒辦法像類常量那樣即定義常量狀態碼,又在map裏放對應的說明信息,只能經過註釋給開發人員用的時候看。

 申哥的這種作法算是一箭雙鵰,在一個常量類裏,定義多個靜態的枚舉,枚舉類定義兩個參數的構造器,一個至關於key,一個是value,屬性也是final類型的,每一個枚舉對應實體對象的一種狀態,甚好。

代碼:

複製代碼
public class Constants {
    public static enum Dict{
        PROSTA("PROSTA","產品狀態"),
        COUNTRY("COUNTRY","國家"),
        
        YWLX("YWLX","業務類型"),
        INDUSTRYCOMPANYTYPE("IndustryCompanyType","公司類型"),
        JSFS("JSFS","結算方式"),
        COMMISSIONTYPE("COMMISSIONTYPE","返傭類型"),
        BALUNITTYPE("BALUNITTYPE","結算單位類型"),
        ORDERSTATS("OrderStats","訂單狀態"),
        BACKORDERSTATUS("BackOrderStatus","退單審覈狀態"),
        BUSINESSPAYMENT("BusinessPayment","業務款項"),
        ENABLESTATE("enableState","啓用禁用"),
        APPROVESTATE("approveState","審批狀態"),
//        分銷系統所需是商品系統的xml
        PRODUCTCONTENTTYPE("productContentType","商品內容分類"),
        IDENTITY("identity","適應人羣"),
        AREA("area","領區"),
        VISATYPE("visatype","簽證類型"),
        SERVICETYPE("serviceType","公證認證商品內容分類"),
        PRODUCTTYPEQUALITY("productTypeQuality","公證認證商品性質"),
        EXPRESSTYPE("expresstype","公證認證加急種類"),
        IDETIFICATIONTYPE("identificationType","認證類別"),
        QYKHLX("QYKHLX","客戶類型"),
        ZILIAONAME("ziliaoName","資料名稱"),
        YESORNO("yesOrNo","是否");

        
        
        private Dict(String value,String name){
            this.value=value;
            this.name=name;
        }
        private final String value;
        private final String name;
        
        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     * 訂單狀態
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-14
     */
    public static enum OrderStats{
        
        DELETE(0,"刪除"),RESERVE(1,"訂單預約"),CONFIRM(2,"訂單確認"),COMPLETE(3,"訂單完成"),CLOSE(4,"訂單關閉");
        
        private OrderStats(Integer value,String name){
            this.value = value;
            this.name = name;
        }
        private final Integer value;
        private final String name;
        
        public Integer getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
        
    }
    /**
     * 性別
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-14
     */
    public static enum sex{
        
        MAN("1","男"),FEMAN("2","女");
        
        private sex(String value,String name){
            this.value = value;
            this.name = name;
        }
        private final String value;
        private final String name;
        
        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
        
    }
    /**
     * 退單審覈狀態
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-14
     */
    public static enum BackOrderStatus{
        WAIT(1,"待審覈"),AUDIT(2,"審覈中"),PASS(3,"審覈經過"),NOTPASS(4,"審覈不經過");
        private BackOrderStatus(Integer value,String name){
            this.value = value;
            this.name = name;
        }
        private final Integer value;
        private final String name;
        
        public Integer getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     * 結算方式
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-14
     */
    public static enum jiesuan{
        XIANJIE("1","現結"),YUEJIE("2","月結");
        private jiesuan(String value,String name){
            this.value = value;
            this.name = name;
        }
        private final String value;
        private final String name;
        
        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     * 業務款項
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-14
     */
    public static enum BusinessPayment{
        VISA("FUND18","簽證費"),PREMIUMS("FUND07","保險"),DEPOSIT("FUND10","押金"),CANCELLING("FUND12","取消金"),FUND20("FUND20","單項服務"),FUND14("FUND14","認證費"),FUND09("FUND09","團款");
        private BusinessPayment(String value,String name){
            this.value = value;
            this.name = name;
        }
        private final String value;
        private final String name;
        
        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     * 通用的啓用禁用狀態
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-14
     */
    public static enum EnableState{
        DISABLE(0,"禁用"),ENABLE(1,"啓用");
        private EnableState(Integer value,String name){
            this.value = value;
            this.name = name;
        }
        private final Integer value;
        private final String name;
        
        public Integer getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     * 通用的審批狀態
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-14
     */
    public static enum ApproveState{
        REJECT(0,"不經過"),PASS(1,"經過");
        private ApproveState(Integer value,String name){
            this.value = value;
            this.name = name;
        }
        private final Integer value;
        private final String name;
        
        public Integer getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     * 通用的是否
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-14
     */
    public static enum YesOrNo{
        NO(0,"否"),YES(1,"是");
        private YesOrNo(Integer value,String name){
            this.value = value;
            this.name = name;
        }
        private final Integer value;
        private final String name;
        
        public Integer getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     * 業務狀態
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-18
     */
    public static enum ServiceStatus{
        NORMAL(1,"正常辦理"),CHANGEING(2,"應收變動中"),BACKING(3,"退單中"),BACK(4,"退單");
        private ServiceStatus(Integer value,String name){
            this.value = value;
            this.name = name;
        }
        private final Integer value;
        private final String name;
        
        public Integer getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     *  支付狀態
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-16
     */
    public static enum PayStatus{
        NOTPAY("01","未支付"),PARTPAY("02","部分支付"),FINISHPAY("03","支付完成");
        private PayStatus(String value,String name){
            this.value = value;
            this.name = name;
        }
        private final String value;
        private final String name;
        
        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    public static enum DeleteStatus{
        NORMAL(1,"正常"),DELETE(0,"刪除");
        private DeleteStatus(Integer value,String name){
            this.value = value;
            this.name = name;
        }
        private final Integer value;
        private final String name;
        
        public Integer getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     *  訂單類型,主要是判斷訂單是從哪一個系統推送過來的,
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-16
     */
    public static enum OrderType{
        SALE("DDLY010301","ERP"),DISTRIBUTION("DDLY0104","分銷平臺");
        private OrderType(String value,String name){
            this.value = value;
            this.name = name;
        }
        private final String value;
        private final String name;
        
        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    public static enum CommonFieldEnum {
        DBID("dbid",UUID.randomUUID().toString().replace("-", "")), //主鍵
        CREATEPERSONNAME("createpersonname","username"),//建立人姓名
        CREATEPERSONCODE("createpersoncode","usercode"),//建立人姓名
        CREATEUSTIME("createtime",new Date()),//建立時間
        UPDATEPERSONNAME("updatepersonname","username"),//更新人姓名
        UPDATEPERSONCODE("updatepersoncode","usercode"),//更新人姓名
        UPDATETIME("updatetime",new Date()),//更新時間
        ACTIONPERSONNAME("actionpersonname","username"),//操做人姓名
        ACTIONPERSONCODE("actionpersoncode","usercode"),//操做人code
        ACTIONTIME("actiontime",new Date()),//操做時間
        ;
        private CommonFieldEnum(String value, Object type) {
            this.value = value;
            this.type = type;
        }

        private final String value;
        private final Object type;
        
        public String getValue() {
            return value;
        }
        public Object getType() {
            return type;
        }
    }

    /**
     *  業務類型
     * <p>Company:rayootech</p>
     * @author xudf
     * @date 2016-6-17
     */
    public static enum BusinessType{
        NOTARY("YWLX09","簽證-公證認證"),VISA("YWLX10","簽證-單辦簽證"),NOTVISA("YWLX16","簽證其餘"),INSURANCE("YWLX11","保險-單辦保險");
        private BusinessType(String value,String name){
            this.value = value;
            this.name = name;
        }
        private final String value;
        private final String name;
        
        public String getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    /**
     * 鎖單狀態
     * <p>Company:rayootech</p>
     * @author zhangxueshen
     * @date 2016-6-16
     */
    public static enum LockStatus{
        NORMAL(0,"正常"),RECEIVCHANGE(1,"應收變動鎖單中"),SEALED(2,"客人封存更鎖單中"),BACK(3,"退單更鎖單中");
        private LockStatus(Integer value,String name){
            this.value = value;
            this.name = name;
        }
        private final Integer value;
        private final String name;
        
        public Integer getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }
    
    
    
    public static void main(String[] args) {
        String key = Constants.ServiceStatus.NORMAL.getName();
        int value = Constants.ServiceStatus.NORMAL.getValue();
        System.out.println(key+":"+ value);
        
    }
}
複製代碼

OK說完了

轉載:https://www.cnblogs.com/lihaoyang/p/6913295.html

相關文章
相關標籤/搜索