Programmatically implementing an interface that combines some instances of the same interface in various specified ways

余生颓废 提交于 2019-12-05 20:14:18

I would have suggested dynamic proxies - is it really so much slower than a regular method call these days - I've heard that reflection does quite a bit of magic under the covers to speed repeated method calls. (And if it is 100x slower, are you sure you will you notice? Ok, just re-read your question - you'll notice!)

Otherwise, you basically have the solution in your question: Use a Command object to wrap each method in your interface. You can then pass each instance in the collection of interfaces to the command object for processing.

Of course, if you're feeling brave and adventurous, you could generate the implementation of your command objects, and the implementation of the combiner interface using dynamic class generation, with cglib, javassist, orther dynamic bytecode generator. That would avoid the boilerplate.

You may also have some success with aspects, particularly aspectJ with compile-time or load-time weaving, so you avoid reflection overhead. Sorry I can't give details.

You can reverse your combiners:

@Override
public String bar(int baz)
{
    //for (Foo f:combiner.combineSomeWay())// returns Iterator<Foo>
    for (Foo f:combiner) //combiner must implement Iterable<Foo> or Iterator<Foo>
    {
        // 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(); 
}

Not a one-liner but easier to understand. That would be more complex if your methods throw exceptions though. You will need try/catch block and addException method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!