【发布时间】:2017-06-01 04:09:15
【问题描述】:
我创建了一个代码,它必须将 ContentDataType 转换为 MIME 类型。例如 - ContentDataType 是一个简单的 String 就像 ImageJPEG 现在我使用 MediaType.IMAGE_JPEG_VALUE 将其转换为 image/jpeg。但我使用 switch 来做到这一点。这是一个代码:
public static String createContentType(ContentDataType contentDataType) {
String contentType;
switch (contentDataType) {
case IMAGE_JPG:
contentType = MediaType.IMAGE_JPEG_VALUE;
break;
//next media types
}
return contentType;
}
有什么更好更优雅的方法来做到这一点?我不想使用if,但也许有一些多态性?你能给我一些提示吗?
【问题讨论】:
-
也许可以创建一个地图
-
具有更多代码但可能提供更灵活/动态解决方案的东西是从
interface开始,它可以采用ContentDataType并返回String,然后你会创建一个注册表,它将通过ContentDataType映射interface,因此您只需将ContentDataType传递给注册表,然后根据注册转换器的可用性将String或null传回.. . 作为一个想法 -
但地图需要用值填充。所以我需要做类似
put(ContentDataType, MediaType.Extenstion)的事情。我说的对吗?
标签: java coding-style switch-statement refactoring