Java 枚举 单例模式 & 当作表使用
枚举是天然单例模式,所以属性添加final ,保证不会被篡改,同时去掉set方法
@ToString
@AllArgsConstructor
public enum EnumBoolean {
/**
* 布尔型
*/
TRUE(1),FALSE(0);
public final Integer value;
}
当作一个表使用:每一个变量都是一个字段。这样可以将数据库中的一些常量写在枚举中,减少IO的次数
/**
* 山东牌照
*/
@ToString
public enum LicensePlateEnum {
A(1, "鲁A", "济南"), B(2, "鲁B", "青岛"), C(3, "鲁C", "淄博"), D(4, "鲁D", "枣庄"),
E(5, "鲁E", "东营"), F(6, "鲁F", "烟台"), G(7, "鲁G", "潍坊"), H(8, "鲁H", "德州"),
J(9, "鲁J", "泰安"), K(10, "鲁K", "威海"), L(11, "鲁L", "日照"), M(12, "鲁M", "滨州"),
N(13, "鲁N", "德州"), P(14, "鲁P", "聊城"), Q(15, "鲁Q", "临沂"), R(16, "鲁R", "菏泽"),
U(17, "鲁U", "青岛增补"), Y(18, "鲁Y", "烟台增补");
LicensePlateEnum(Integer code, String city, String cityName) {
this.code = code;
this.city = city;
this.cityName = cityName;
}
@Getter
private final Integer code;
@Getter
private final String city;
@Getter
private final String cityName;
public static LicensePlateEnum getByCity(String city){
if(StringUtils.isEmpty(city)){
return null;
}
for (LicensePlateEnum value : LicensePlateEnum.values()) {
if(value.getCity().equals(city)){
return value;
}
}
return null;
}
}
单例:
https://www.cnblogs.com/happy4java/p/11206105.html
常量表:
https://www.cnblogs.com/pzyin/p/12534640.html
end
通过知识/经验的分享,节省开发者的时间.