Java如何通过"枚举的枚举"表示二级分类的业务场景
作者:编程经验分享
这篇文章主要介绍了Java如何通过"枚举的枚举"表示二级分类的业务场景问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
问题
一般在开发中,会使用枚举类穷举特定的业务字段值。
比如用枚举类来表示业务中的类型,不同的类型对应的不同的业务逻辑。
但是如果一个类型下会有不同多个的子类型,这时候一个枚举类就不能够完全表示这个业务逻辑了。
如何解决
在 Java编程思想 这本书的枚举章节中,有一段 枚举的枚举 代码示例,就能够很好的表示上面问题的业务场景。
代码
业务场景
4 张业务数据表 A B C D,按资源类型来分类,其中 A B 表属于农用地资源,C D 表属于森林资源。
一级资源类型枚举类
public enum Resource {
FARM(0, "农用地", 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());
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
