我想创建一个动态选择实现的Abstract Builder。
我的尝试是:
1。为我的构建器创建界面:
public interface JSONFormatterAbstractBuilder {
Object format(Object object);
}
2。创建静态的构建器列表以获取适合该工作的构建器:
public abstract class BuilderMap {
private static Map<Class<?>, JSONFormatterBuilder> builderMap = new HashMap<>();
public static JSONFormatterBuilder getBuilder(Class<?> classOfObjectToBeFormatted) {
return builderMap.get(classOfObjectToBeFormatted);
}
public static boolean hasBuilder(Class<?> classOfObjectToBeFormatted) {
return builderMap.containsKey(classOfObjectToBeFormatted);
}
public static JSONFormatterBuilder setBuilder(Class<?> baseObjectClass,
JSONFormatterBuilder builder) {
return (JSONFormatterBuilder) builderMap.put(baseObjectClass, builder);
}
}
3。创建一个使用静态初始化程序实现构建器接口的类,以将实例添加到构建器实现的列表中:
public class BooleanOptBuilder implements JSONFormatterBuilder {
private static BooleanOptBuilder instance = new BooleanOptBuilder();
private BooleanOptBuilder() {}
public static BooleanOptBuilder getInstance() {
return instance;
}
static {
//The static initializer to add the instance to the list of implementations
BuilderMap.setBuilder(boolean_opt_t.class, instance);
}
@Override
public Object format(Object raw) {
if(!(raw instanceof boolean_opt_t))
throw new InputMismatchException("Expecting boolean_opt_t, found : "+raw.getClass().getCanonicalName());
boolean_opt_t object = (boolean_opt_t) raw;
//Does the work ...
}
}
4。我打算如何使用构建器的主要内容的摘录
boolean_opt_t booleanOptObject;
//Initialization of the variable
JSONFormatterBuilder builder = BuilderMap.getBuilder(boolean_opt_t.class);
Object o = builder.format(booleanOptObject);
我通过这种方式在构建器的执行过程中级联动态地使用正确的工厂。接下来,我想将新的构建器添加到地图中,只需将它们放在类路径中,例如通过Maven依赖项(因此,排除了枚举所有现有构建器的BuilderMap中的静态初始化器,因为要添加新的构建器,您将必须修改BuilderMap类)。
但是,当我尝试使用BuilderList时,对于我要求的类型,内容为空。我认为在尝试调用“格式”方法时未加载此构建器的类,因此未填充构建器的映射。而且提取的代码无法正常工作,并在builder.format(..)
上抛出NullPointerException。
所以我对我的帖子有一些疑问:
谢谢。