[英]Refactoring: when visitor pattern can't be used to replace switch/instanceof
我正在尝试使用instanceof对一段代码进行重构,以确定类型。 我认为,在这种情况下,子类型化/多态性将无法工作(即使在这种情况下可能会产生过多的杀伤力),并且访客模式在这里将无法正常工作,因为我无法将接受方法添加到注解。 还有其他方法可以使这种代码更清晰/更具可读性吗?
for (Annotation annotation : method.getAnnotations()) {
if (annotation instanceof DELETE) {
setHttpMethod(annotation.annotationType().getSimpleName(), false);
parsePath(((DELETE) annotation).value());
} else if (annotation instanceof GET) {
setHttpMethod(annotation.annotationType().getSimpleName(), false);
parsePath(((GET) annotation).value());....
删除和获取看起来像这样
public @interface DELETE {
String value() default "";
}
public @interface GET {
String value() default "";
}
用法示例:
class Example {
@DELETE("value")
Response method() {
...
}
}
DELETE delete = method.getAnnotation(DELETE.class);
if (delete != null) {
...
}
GET get = method.getAnnotation(GET.class);
if (get != null) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.