Saturday, January 15, 2005

delegates in java

so, this c# project that i have to convert to java uses delegates. i hadn't worked with delegates in c# before, so studying the delegates usage in the project was quite interesting. after some research i decide not to use reflection or anything else as a means to implement delegates in java. instead i take a to rewrite the code that uses delegates to simple function calls constructs. delegates here are used to make a templates approach to some tasks - for example visit a hierarchy of objects each of which may have subhierarchy and so on. with delegates used it makes it easy to go down the tree of objects and apply some operation on each of them AND - what is important -the operation would be a delegate so many operations can be executed by calling a single method that traverses the tree. or sort of :)
so my decision - as i cant use template code - is to generally make a tree traversal in a distinct method for each operation.
so instead of

internal override void visitHierarchy(CollectionVisitor visitor)
{
base.visitHierarchy(visitor);

foreach (SomeObject Obj in collection1)
Obj.visitHierarchy(visitor);
foreach (SomeObject Obj in collection2)
Obj.visitHierarchy(visitor);
}

there will be a similar block of code, but implemented for the different operations that need to be executed:

public void visitWithOperation1()
{
super.visitWithOperation1();

foreach (SomeObject Obj in collection1)
Obj.visitWithOperation1();
foreach (SomeObject Obj in collection2)
Obj.visitWithOperation1();
}

and

public void visitWithOperation2()
{
super.visitWithOperation2();

foreach (SomeObject Obj in collection1)
Obj.visitWithOperation2();
foreach (SomeObject Obj in collection2)
Obj.visitWithOperation2();
}


of course there isn't foreach in java... but hope you get the idea....
so this is a little bit tedious approach to rewriting delegates in java, but i hope it works for now