java - 使用接口的独占方法进行比较,没有 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);
}
但是我们都知道这是怎么回事,意大利面条代码......所以,我的问题是:找到并返回该端点的最佳方法是什么?
解决方案
推荐阅读
- excel - 如何在 vba 中进行自定义 vlookup?
- react-native - 如何在 React-Navigation 上传递道具,以便导航组件可以在这些道具更改时重新渲染
- node.js - InversifyJS 注入 express.Application
- apache-kafka - 当 Kafka 主题只有一个分区和多个消费者时会发生什么?
- linux - 使用 SAS EG 包含文件时如何指定本地目录?
- php - PHP ksort 意外行为
- python - 将标头值传递给 django 中的获取请求
- ios - 照片库中的视频磁贴
- azure - 单一分区上的 CosmosDB 跨分区查询错误
- typescript - TypeScript:可区分联合的通用 switchExpression 函数