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

标签 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 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);

我不知道如何让我对每种类型执行操作。也就是说,“objects”的 documentSlice.get (“content”) 或“appeals.objects”的 documentSlice.get(“data”).get(“person”) 。有什么想法吗?

最佳答案

可能的变体之一是 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);

关于java - Enum实现部分业务逻辑的能力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60096288/

相关文章:

java - 菜单弹出时面板缺少重叠部分

java - 在 Java 中重写可变参数

c# - 使用运算符 & |关于 C# 中的枚举?

angular - 如何检测 Angular 中的死代码或未使用的代码?

refactoring - 这种对流结构的控制是好的做法吗?

java - 合并 JPA 实体返回旧值

javax.jms.JMSException : MQJMS2002: failed to get message from MQ queue

oracle - 重构PL/SQL触发器-提取过程

mvvm - RelayCommand <enum>上的RaiseCanExecuteChanged()不会导致CanExecute()被调用

postgresql - postgres 枚举与 golang pgx