在我看来,这听起来像是策略模式将满足您的需求(GOF - http://en.wikipedia.org/wiki/Strategy_pattern)。
我不清楚你希望它有多动态。拥有一个接口的两个实现和一个选择器方法是最简单的。但是您也可以动态地动态生成接口的实现,这可能对您来说太过分了。无论哪种方式,策略模式都可以抽象出这种复杂性,并使您能够根据所需的任何运行时标准选择不同的行为。
这是一个动态加载类的示例,假设您已经知道完全限定的类名并且该对象具有无参数构造函数:
Class c = Class.forName("java.lang.Object");
Object o = c.newInstance();
System.out.println( "o = " + o );
对于这种情况,您需要捕获的错误是:InterruptedException、ClassNotFoundException、IllegalAccessException、InstantiationException;很多,但只是以相同的方式处理它们并拒绝用户的选择。
如果你需要一个带参数的构造函数,那么:
Class c = Class.forName("java.lang.String");
Constructor cons = c.getConstructor( String.class ); // the args here are the expected types for the constructor that you require on the class
String s = (String) cons.newInstance( "hello" );
这将添加更多必须捕获的异常:InterruptedException、ClassNotFoundException、IllegalAccessException、InstantiationException、NoSuchMethodException、InvocationTargetException。但是再次以与以前相同的方式拒绝用户选择。