In Java I’m looking for a generic template that means arrays of a given type (say Foo), will allow instance method calls upon the array. Behind-the-scenes this would translate to iterating over all Foo instances in the array, and calling the instance method upon each one.
Perhaps some code will demonstrate this point better:
public class Foo{
public Foo(){}
public void Method1(){}
}
So you have:
Foo foo = new Foo();
foo.Method1();
But could you make some generic template for your custom types that inherently made this kind of thing possible:
Foo[] foos = new Foo[]{new Foo(),new Foo(), new Foo()};
foos.Method1();
Which is essentially syntactic sugar for:
foreach(Foo f : foos){
f.Method1();
}
My motivation is so that someone can use varargs such that:
someHelper(fooInstance1,fooInstance2).Method1()
Where someHelper() returns the Foo[].
If each Method1() invocation returned a value, it would be even better if this was wrapped in to an array of return values (where ReturnVals.size == Foos.size).
In the worst-case I’d have to write a separate class to achieve this for each type I need to have this work for, possibly using interfaces to describe functionality that applies to single instances and arrays of instances.
Is there any Java magic, Design Pattern or Generic jiggery-pokery that can elegantly achieve this?
Further, if not, do any languages facilitate this inherently?
I appreciate it wouldn’t work for all scenarios, but that’s at the discretion of the programmer I suppose.
Many thanks
You are calling for the Composite Pattern. You can find a componentized generic and reusable implementation in the project PerfectJPattern make sure to checkout the Composite documentation page and the example that matches the example in the GoF book.
Verbatim copy of the relevant part of the example, say you have IGraphic interface and a few implementations, e.g. Rectangle and Line, then you can do:
This is how it would work for your specific case:
Note that the
ICompositereusable implementation holds the actual composite and it does not implement/offer theFoointerface, you rather have to get hold of it via thegetComponentmethod. This is a small nuisance and it is needed because there is no other way in Java to create an instance of something (in this caseComposite) that implements any arbitrary and statically unknown interface. The best I can do is give you aCompositethat underneath builds a true composite component for you and returns your desired interface typeFoo. This is implemented using Dynamic proxies, but the implementation is type-safe and fully componentized i.e. you dont have to create any new Composite arrays that implement your interface.