如何用更好的解决方案替换 switch 语句 - 干净的代码提示
我创建了一个代码,它必须将 ContentDataType
转换为 MIME
类型.例如 - ContentDataType
是一个简单的 String
像 ImageJPEG
现在我使用 MediaType.IMAGE_JPEG_VALUE
将其转换为 <代码>图像/JPEG代码>.但我使用 switch 来做到这一点.这是一个代码:
I created a code, which have to convert ContentDataType
into MIME
types. For example - ContentDataType
is a simple String
like ImageJPEG
and now I use MediaType.IMAGE_JPEG_VALUE
to convert it into image/jpeg
. But I use switch to do this. This is a code:
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
,但可能有一些多态性?你能给我一些提示吗?
What is a better and elegant way to do this? I do not want to use if
, but maybe some polymorphism? Can you give me any hints?
推荐答案
如果你准备只使用一个 if/else
你可以这样做:
If you are ready to use just one if/else
You can do something like this :
private static Hashtable<String, String> types = new Hashtable<>();
static{
types.put(IMAGE_JPG, MediaType.IMAGE_JPEG_VALUE);
types.put(IMAGE_PNG, MediaType.IMAGE_PNG_VALUE);
types.put(IMAGE_XXX, MediaType.IMAGE_XXX_VALUE);
}
public static String createContentType(ContentDataType contentDataType) {
if types.containsKey(contentDataType)
return types.get(contentDataType);
else
throw new RuntimeException("contentDataType not supported");
}
}
这允许您将新支持的类型添加到 Hashtable 中,而不必处理一长串 if/else if/else
.
This allows you to add new supported types into the Hashtable whitout having to deal with a long sequence of if/else if/else
.
相关文章