Java如何通過"枚舉的枚舉"表示二級分類的業(yè)務(wù)場景
問題
一般在開發(fā)中,會使用枚舉類窮舉特定的業(yè)務(wù)字段值。
比如用枚舉類來表示業(yè)務(wù)中的類型,不同的類型對應(yīng)的不同的業(yè)務(wù)邏輯。
但是如果一個類型下會有不同多個的子類型,這時候一個枚舉類就不能夠完全表示這個業(yè)務(wù)邏輯了。
如何解決
在 Java編程思想 這本書的枚舉章節(jié)中,有一段 枚舉的枚舉 代碼示例,就能夠很好的表示上面問題的業(yè)務(wù)場景。
代碼
業(yè)務(wù)場景
4 張業(yè)務(wù)數(shù)據(jù)表 A B C D,按資源類型來分類,其中 A B 表屬于農(nóng)用地資源,C D 表屬于森林資源。
一級資源類型枚舉類
public enum Resource {
FARM(0, "農(nóng)用地", Table.Farm.class),
FOREST(1, "森林", Table.Forest.class);
static {
typeMap = Stream.of(values()).
collect(Collectors.toMap(e -> e.getValue(), e -> e));
}
private static final Map<Integer, Resource> typeMap;
private final int value;
private final String desc;
private final Table[] tables;
Resource(int value, String desc, Class<? extends Table> kind) {
this.value = value;
this.desc = desc;
this.tables = kind.getEnumConstants();
}
public int getValue() {
return value;
}
public String getDesc() {
return desc;
}
public Table[] getTables() {
return tables;
}
public static Resource getEnum(int value) {
return typeMap.get(value);
}
}二級資源類型枚舉類
public interface Table {
enum Farm implements Table {
TABLE_A("TABLE_A"),
TABLE_B("TABLE_B");
private final String tableName;
Farm(String tableName) {
this.tableName = tableName;
}
public String getTableName() {
return tableName;
}
}
enum Forest implements Table {
TABLE_C("TABLE_C"),
TABLE_D("TABLE_D");
private final String tableName;
Forest(String tableName) {
this.tableName = tableName;
}
public String getTableName() {
return tableName;
}
}
String getTableName();
}測試
public class Test {
public static void main(String[] args) {
for (Table table : Resource.getEnum(0).getTables()) {
System.out.println(table.getTableName());
}
for (Table table : Resource.getEnum(1).getTables()) {
System.out.println(table.getTableName());
}
}
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java JDK動態(tài)代理(AOP)用法及實現(xiàn)原理詳解
在本篇文章了小編給大家整理的是一篇關(guān)于Java JDK動態(tài)代理(AOP)用法及實現(xiàn)原理詳解內(nèi)容,有需要的朋友們可以參考學習下。2020-10-10
圖文講解IDEA中根據(jù)數(shù)據(jù)庫自動生成實體類
這篇文章主要以圖文講解IDEA中根據(jù)數(shù)據(jù)庫自動生成實體類,本文主要以Mysql數(shù)據(jù)庫為例,應(yīng)該會對大家有所幫助,如果有錯誤的地方,還望指正2023-03-03

