Java如何通過"枚舉的枚舉"表示二級分類的業(yè)務場景
更新時間:2024年06月17日 09:40:10 作者:編程經(jīng)驗分享
這篇文章主要介紹了Java如何通過"枚舉的枚舉"表示二級分類的業(yè)務場景問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
問題
一般在開發(fā)中,會使用枚舉類窮舉特定的業(yè)務字段值。
比如用枚舉類來表示業(yè)務中的類型,不同的類型對應的不同的業(yè)務邏輯。
但是如果一個類型下會有不同多個的子類型,這時候一個枚舉類就不能夠完全表示這個業(yè)務邏輯了。
如何解決
在 Java編程思想 這本書的枚舉章節(jié)中,有一段 枚舉的枚舉 代碼示例,就能夠很好的表示上面問題的業(yè)務場景。
代碼
業(yè)務場景
4 張業(yè)務數(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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
mybatis連接MySQL8出現(xiàn)的問題解決方法
這篇文章主要介紹了mybatis連接MySQL8出現(xiàn)的問題解決方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10Java使用選擇排序法對數(shù)組排序?qū)崿F(xiàn)代碼
這篇文章主要介紹了Java使用選擇排序法對數(shù)組排序?qū)崿F(xiàn)代碼,需要的朋友可以參考下2014-02-02