Enum实现部分业务逻辑的能力

Enum's ability to implement part of the business logic

正在尝试重构代码。现在代码是:

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 ("content") 用于 'objects' 或 documentSlice.get("data").get("person") 用于 'appeals.objects'。有什么想法吗?

一种可能的变体是 Enum class:

中的抽象方法
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);