1. Round: function pointers vs. delegates vs. anonymous classes
C++ functions are knocked out by the first hit, since class methods can’t be ones, and they are unsafe
C# delegates seem to have good foot work, they are easy to use,
// definition
delegate void Foo(object arg);
// implementation
Object anObject = ..;
Foo foo = delegate(object arg) {
Console.WriteLine(arg.ToString() + anObject);
};
// calling
foo("Hello");
but there comes Java, leaves its defense and hits back with it’s anonymous classes, which are even more powerfull , beeing object oriented by encapsulating data:
// definition
interface Delegates {
void foo(Object arg);
void bar(); // yeah not only one function
}
// implementation
final Object anObject = ..;
Delegates delegates = new Delegates() {
public void foo(Object arg) {
System.out.printLine(arg.ToString() + anObject);
}
public void bar() {
System.out.printLine("Bar");
}
};
// calling
delegates.foo("Hello");
delegates.bar();
so far a slightly advantage for Java. But wait, there comes X - the underdog, which is exactly like using Java’s anomymous methods, but has a nice syntax sugar for interfaces with only a single method:
// definition
interface Delegate {
void foo(Object arg);
}
// implementation
final Object anObject = ..;
Delegates delegate = new Delegate.foo(Object arg) { // the single method, right behind the interface name
System.out.printLine(arg.ToString() + anObject);
};
// calling
delegate.foo("Hello");
nice, isn’t it
to be continued