簡體   English   中英

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類中的抽象方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM