如何改进两个接口之间的面向对象设计

问题描述 投票:0回答:0

在下面的示例代码中,我们如何摆脱具体类的 if-else 阶梯,即。

NoProcesssorFoundError
&
UnknownError
。我可以提取
Event1
Event2
之间的接口,并将它们的处理器传递给处理函数,因为
process1
process2
几乎相同,除了输入及其过程。然而,如何摆脱错误具体类的if-else阶梯

public class EventProcessor {

    public void onEvent1(Event1 event1) {
        val result = process1(event1);
        if(result instanceof NoProcesssorFoundError) {
            event1.setStatus(RETRYABLE);
            ...
        } else(result instanceof UnknownError) {
            event1.setStatus(FAILED);
            ...
        }
    }

    public void onEvent2(Event2 event2) {
        val result = process2(event2);
        if(result instanceof NoProcesssorFoundError) {
            event2.setStatus(REJECTED);
            ...
        } else(result instanceof UnknownError) {
            event2.setStatus(FAILED);
            ...
        }
    }

    private Error process1(Event1 event1) {
        Event1processors.process(event1)
        ....
        if(true) {
            return new NoProcessorFoundError();
        } else {
            return new UnknownError();
        }
    }

    private Error process2(Event2 event2) {
        Event2processors.process(event2)
        ....
        if(true) {
            return new NoProcessorFoundError();
        } else {
            return new UnknownError();
        }
    }

    abstract class Error {
        class NoProcessorFoundError extends Error {}
        class UnknownError extends Error {}
        ...
    }
}
java oop design-patterns class-design ooad
© www.soinside.com 2019 - 2024. All rights reserved.