This is an alternative way of writing the same.
I think, it is the Visitor pattern, although all the times I have seen it I don't quite get it ( the Visitor documentation ) so, probably this is something else.
Anyway, the idea is to use anonymous inner classes ( fake Java "closures" ) and write the iteration once.
public class IterationSample {
public static void main( String [] args ) {
Foo [] items = new Foo[0]; // get it from somewhere ....
iterate( items , new _(){void with( Foo f ){
f.doSomething();
}});
iterate( items , new _(){void with( Foo f ){
f.doSomethingElse();
}});
iterate( items , new _(){void with( Foo f ){
f.doBar();
}});
}
// write the loop once.
static void iterate( Foo [] items, _ visitor ) {
for( Foo f : items ) {
visitor.with( f );
}
}
}
The Foo object would be the object would be your object.
// Not really abstract just for the sake of the sample. Use your own.
abstract class Foo {
abstract void doSomething();
abstract void doSomethingElse();
abstract void doBar();
}
Finally this is the "visitor"
// made abstract instead of interface just to avoid having to type
// "public" each time.
abstract class _ {
abstract void with( Foo f );
}
It is a shame I can't avoid the return type of the method.
Otherwise this
iterate( items ,new _(){ with( Foo f ){
Would read as:
Iterate items "noise" with foo
Why would you do that when you can do this?
Because that way you can have an array of operations:
_ [] operations = {
new _(){void with( Foo f ){
f.doSomething();
}},
new _(){void with( Foo f ){
f.doSomethingElse();
}},
new _(){void with( Foo f ){
f.doBar();
}}
};
And iterate them :)
for( _ andPerformAction : operations ) {
iterate( items , andPerformAction );
}
There might be some situations for this, although I can think of any right now =-S