Java如何通過(guò)"枚舉的枚舉"表示二級(jí)分類的業(yè)務(wù)場(chǎng)景
問(wèn)題
一般在開發(fā)中,會(huì)使用枚舉類窮舉特定的業(yè)務(wù)字段值。
比如用枚舉類來(lái)表示業(yè)務(wù)中的類型,不同的類型對(duì)應(yīng)的不同的業(yè)務(wù)邏輯。
但是如果一個(gè)類型下會(huì)有不同多個(gè)的子類型,這時(shí)候一個(gè)枚舉類就不能夠完全表示這個(gè)業(yè)務(wù)邏輯了。
如何解決
在 Java編程思想 這本書的枚舉章節(jié)中,有一段 枚舉的枚舉 代碼示例,就能夠很好的表示上面問(wèn)題的業(yè)務(wù)場(chǎng)景。
代碼
業(yè)務(wù)場(chǎng)景
4 張業(yè)務(wù)數(shù)據(jù)表 A B C D,按資源類型來(lái)分類,其中 A B 表屬于農(nóng)用地資源,C D 表屬于森林資源。
一級(jí)資源類型枚舉類
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);
}
}二級(jí)資源類型枚舉類
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();
}測(cè)試
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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java JDK動(dòng)態(tài)代理(AOP)用法及實(shí)現(xiàn)原理詳解
在本篇文章了小編給大家整理的是一篇關(guān)于Java JDK動(dòng)態(tài)代理(AOP)用法及實(shí)現(xiàn)原理詳解內(nèi)容,有需要的朋友們可以參考學(xué)習(xí)下。2020-10-10
圖文講解IDEA中根據(jù)數(shù)據(jù)庫(kù)自動(dòng)生成實(shí)體類
這篇文章主要以圖文講解IDEA中根據(jù)數(shù)據(jù)庫(kù)自動(dòng)生成實(shí)體類,本文主要以Mysql數(shù)據(jù)庫(kù)為例,應(yīng)該會(huì)對(duì)大家有所幫助,如果有錯(cuò)誤的地方,還望指正2023-03-03
SpringBoot整合chatGPT的項(xiàng)目實(shí)踐
本文主要介紹了SpringBoot整合chatGPT的項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
Gradle構(gòu)建多模塊項(xiàng)目的方法步驟
這篇文章主要介紹了Gradle構(gòu)建多模塊項(xiàng)目的方法步驟,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05

