Java 枚举';s实现部分业务逻辑的能力
试图重构代码。现在代码是:Java 枚举';s实现部分业务逻辑的能力,java,enums,refactoring,Java,Enums,Refactoring,试图重构代码。现在代码是: if ("objects".equals(type)) { Object oldJson = oldData.get("content"); Object newJson = newData.get("content"); } else if ("objects.appeals".equals(type)) { Object oldJson = oldData.get("data").get("person"); Object newJ
if ("objects".equals(type)) {
Object oldJson = oldData.get("content");
Object newJson = newData.get("content");
} else if ("objects.appeals".equals(type)) {
Object oldJson = oldData.get("data").get("person");
Object newJson = newData.get("data").get("person");
}
类型的数量要大得多。我只举了2个例子。正在尝试使用枚举进行优化:
public enum HistoryUpdateTypeEnum {
OBJECTS("objects", new Document()),
APPEALS_OBJECTS("appeals.objects", new Document());
HistoryUpdateTypeEnum(String type, Document documentSlice) {
this.type = type;
this.documentSlice = documentSlice;
}
private String type;
private Document documentSlice;
public static HistoryUpdateTypeEnum fromString(String value) {
return Stream.of(values())
.filter(Objects::nonNull)
.filter(v -> v.name().replaceAll("_",".").equalsIgnoreCase(value))
.findAny()
.orElse(null);
}
public Object formSlice(Document data) {
this.documentSlice = data;
return documentSlice.get("content"); // How to make it universal?
}
}
和使用:
HistoryUpdateTypeEnum typeEnum = HistoryUpdateTypeEnum.fromString("objects.appeals");
Document oldData = new Document(......).append(..., ...);
Document newData = new Document(......).append(..., ...);
Object oldJson = typeEnum.formSlice(oldData);
Object newJson = typeEnum.formSlice(newData);
我不知道如何让我对每种类型执行操作。也就是说,documentSlice.get(“内容”)表示“对象”,documentSlice.get(“数据”).get(“人员”)表示“申诉.对象”。有什么想法吗?可能的变体之一是
Enum
类中的抽象方法:
public enum HistoryUpdateTypeEnum {
OBJECTS {
@Override
Object getJson(Document data) {
return data.get("objects");
}
},
...
abstract Object getJson(Document data);
}
然后你可以这样使用它:
HistoryUpdateTypeEnum history = HistoryUpdateTypeEnum .valueOf(type.toUpperCase());
Object oldJson = history.getJson(oldData);
Object newJson = history.getJson(newData);