JAVA常量类的实现方式
前言
众所周知,系统里有很多比如订单状态、审核状态;性别、结算方式、交易类型等属性,这些属性只有几个值,一般用0、1、2、3等的数字标识存入数据库,每次对这些属性所属对象的增删改操作,都会在代码里给状态设置值,由于项目是多人开发的,如果每次设置值的时候都直接set 0、1、2,容易出错,而且状态假设不用0、1、2表示了,用1、2、3表示,这时候所有set状态的地方都得改变,维护麻烦。所以用常量表示状态值,甚好。
据我目前所知,系统里实现常量的方式有三种:
1, 接口常量
2, 类常量
3, 枚举
一:接口常量
Java程序里实现常量,jdk1.5之前,没有枚举类,有的用的接口来实现系统中的常量:
如java的swing里有一个SwingConstant:
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 的含义,必须看类里的注释,知道他表示中心。如果常量很多的话,把所有的常量都放在这一个接口里边,这种方式感觉也不是很友好。
(申哥,瑞友的架构师,我的老乡、偶像)看了申哥以前的项目,发现一个常量类,也是接口常量类,在接口里定义静态内部类,但是比上边这种要好,他可以把不同的功能的常量类进一步分类,看代码:
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