首页 > 解决方案 > 使用接口的独占方法进行比较,没有 if 块

问题描述

我有以下接口:

public interface Endpoint {
    void reply(HttpExchange exchange, Map<String, String> parameters, boolean prettyPrint);
}

public interface Nameable {
    String getName();
}

public interface Patternable { // I seriously suck at naming, you could also suggest a name for this one
    String getPattern();
}

并且有一个管理器类,它提供一个列表来存储端点,以及一个从该列表中获取端点的方法。这就是我迄今为止为该方法所做的:

public Endpoint getEndpoint(String nameORpattern) {
    return endpointList.stream().filter(endpoint -> {
        if (endpoint instanceof Nameable) {
            return ((Nameable) endpoint).getName().equalsIgnoreCase(nameORpattern);
        } else if (endpoint instanceof Patternable) {
            return Pattern.compile(((Patternable) endpoint).getPattern()).matcher(nameORpattern).find();
        } else {
            return false;
        }
    }).findFirst().orElse(null);
}

但是我们都知道这是怎么回事,意大利面条代码......所以,我的问题是:找到并返回该端点的最佳方法是什么?

标签: javainterfaceinterface-segregation-principle

解决方案


推荐阅读