我正在开发一种工具,用户可以使用自己的注释来描述数据处理工作流程(如验证,转换等)。
除了使用现成的注释外,用户还可以自己使用注释:为了做到这一点,他们需要自己声明注释类,然后实现注释处理器(< - 这是这个问题的主要要点)
配置的数据处理方法可能如下所示:
void foo(@Provide("dataId") @Validate(Validator.class) String str) {
doSmth(str);
}
自然有三组注释:
所以我需要做一个选择:要么创建一个接口来处理所有这些类型的注释,它们看起来像这样:
interface GenericAnnotationProcessor {
Object processAnnotation(Annotation annotation, Object processedValue);
}
或者我可以在API中添加3个接口:
interface ProducerAnnotationProcessor {
Object produceInitValue(Annotation annotation);
}
interface TransformerAnnotationProcessor {
Object transformValue(Annotation annotation, Object currentValue);
}
interface ConsumerAnnotationProcessor {
void consumeValue(Annotation annotation, Object currentValue);
}
第一个选项在使用中不是很清楚,但第三个选项使用3个几乎相似的接口污染API。
您会选择什么(首先作为API用户)以及为什么?
谢谢!
答案 0 :(得分:0)
我将创建第一个更通用的接口,然后定义三个不同的实现类。在不知道如何使用它的情况下,我的第一直觉是定义接口和/或基类(取决于在不同处理器之间共享多少通用实现代码),然后在派生中添加专用处理器实现类型,所有whihc共享共同的接口。
在使用API时,我希望声明一个实现GenericAnnotationProcessor的变量,然后根据我的需要分配适当的实现类型。
现在在俄勒冈州的波特兰市很早,但是在这个时刻,我所需要的咖啡因水平的50%,在我看来,它可以提供最大的灵活性,同时最大限度地重复使用cade。
当然,您的实际要求可能会另有规定。 。
希望这很有用!
答案 1 :(得分:0)
深入研究你的问题。
当他们执行类似的任务时,如果有一些差异,Strategy pattern #Example应该会帮助你。
您的问题应该如下所示。
interface GenericAnnotationProcessor {
Object processAnnotation(Annotation annotation, Object processedValue);
}
interface ProducerAnnotationProcessor implements GenericAnnotationProcessor {
}
interface TransformerAnnotationProcessor implements GenericAnnotationProcessor {
}
interface ConsumerAnnotationProcessor implements GenericAnnotationProcessor {
}
现在您可以关注Wiki的示例
class Context {
// map of annotation processors
// register(add/remove) annotation processors to the map
public int executeAnnotationProcessor(Annotation annotation, Object processedValue) {
return locateAnnotationProcessor(annotation).processAnnotation(annotation, processedValue);
}
private GenericAnnotationProcessor locateAnnotationProcessor(Annotation annotation) {
// return expected annotation processor
}
}
我相信你可以理解。
答案 2 :(得分:0)
您可以使用接口扩展接口 More on there
与类类似,您可以使用extends关键字构建接口的继承层次结构,如:
interface Washable {
void wash();
}
interface Soakable extends Washable {
void soak();
}
在此示例中,接口Soakable扩展了接口Washable。因此,Soakable继承了Washable的所有成员。实现Soakable的类必须为Soakable,wash()和soak()声明或继承的所有方法提供实体,或者声明为abstract。请注意,只有接口可以“扩展”其他接口。类不能扩展接口,它们只能实现接口。
希望它有所帮助。