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:
// build the composite
IComposite<IGraphic> myComposite = new Composite<IGraphic>(IGraphic.class);
myComposite.add(new Rectangle());
myComposite.add(new Line());
myComposite.add(new Line());
// use the composite, invokes the IGraphic#draw() in the
// underlying Rectangle and two Line instances
myComposite.getComponent().draw();
This is how it would work for your specific case:
Foo fooInstance1 = new Foo();
Foo fooInstance2 = new Foo();
IComposite<Foo> myComposite = new Composite<Foo>(Foo.class);
myComposite.add(fooInstance1);
myComposite.add(fooInstance2);
// invokes Method1 on instance1 and instance2 transparently
myComposite.getComponent().Method1();
// alternatively do
Foo myCompositeFoo = myComposite.getComponent();
// pass this myCompositeFoo around and do
myCompositeFoo.Method1();
Note that the IComposite
reusable implementation holds the actual composite and it does not implement/offer the Foo
interface, you rather have to get hold of it via the getComponent
method. 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 case Composite
) that implements any arbitrary and statically unknown interface. The best I can do is give you a Composite
that underneath builds a true composite component for you and returns your desired interface type Foo
. 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.