以编程方式实现以各种指定方式组合同一接口的某些实例的接口

实现以各种指定方式组合同一接口的某些实例的接口的最佳方法是什么? 我需要为多个接口执行此操作,并且我希望最小化样板并仍然实现良好的效率,因为我需要将其用于关键生产系统。

这是问题的草图。

抽象地说,我有一个通用的组合器类,它接受实例并指定各种组合器:

class Combiner { I[] instances;  T combineSomeWay(InstanceMethod method) { // ... method.call(instances[i]) ... combined in some way ... } // more combinators } 

现在,假设我想在许多其他界面中实现以下界面:

 Interface Foo { String bar(int baz); } 

我想最终得到这样的代码:

 class FooCombiner implements Foo { Combiner combiner; @Override public String bar(final int baz) { return combiner.combineSomeWay(new InstanceMethod { @Override public call(Foo instance) { return instance.bar(baz); } }); } } 

现在,如果接口有很多方法,这可以很快变长。 我知道我可以使用JavareflectionAPI中的动态代理来实现这样的接口,但通过reflection进行的方法访问要慢一百倍。 那么在这种情况下,样板和reflection的替代方案是什么?

我会建议使用动态代理 – 它现在比常规方法调用慢得多 – 我听说reflection对于加速重复方法调用有很大的魔力。 (如果它慢了100倍,你确定你会注意到吗?好的,重新阅读你的问题 – 你会注意到的!)

否则,您基本上可以在您的问题中找到解决方案:使用Command对象来包装界面中的每个方法。 然后,您可以将接口集合中的每个实例传递给命令对象进行处理。

当然,如果你感觉勇敢和冒险,你可以生成命令对象的实现,并使用动态类生成实现组合器接口,使用cglib,javassist,ororther 动态字节码生成器 。 那样可以避免样板。

您也可以在方面取得一些成功,特别是使用编译时或加载时编织的aspectJ,这样可以避免reflection开销。 对不起,我不能透露细节。

你可以反转你的合成器:

 @Override public String bar(int baz) { //for (Foo f:combiner.combineSomeWay())// returns Iterator for (Foo f:combiner) //combiner must implement Iterable or Iterator { // In case of several ways to combine // add() method should call some temp object // in combiner created (or installed) by // combineSomeWay. // The best temp object to use is Iterator // returned by combiner.combineSomeWay(); combiner.add(f.bar(baz));// or addResult, or addCallResult } // clear (or uninstall) temp object and result // thats why get* method // name here is bad. return combiner.done(); } 

不是单行,但更容易理解。 如果您的方法抛出exception,那将会更复杂。 您将需要try / catch块和addException方法。