What is the Java equivalent of Cocoa delegates?
(I understand that I can have an interface passed to a class, and have that class call the appropriate methods, but I\'m
Best analog to an informal protocol I can think of is an interface that also has an adapter class to allow implementers to avoid implementing every method.
public class MyClass {
private MyClassDelegate delegate;
public MyClass () {
}
// do interesting stuff
void setDelegate(MyClassDelegate delegate) {
this.delegate = delegate;
}
interface MyClassDelegate {
void aboutToDoSomethingAwesome();
void didSomethingAwesome();
}
class MyClassDelegateAdapter implements MyClassDelegate {
@Override
public void aboutToDoSomethingAwesome() {
/* do nothing */
}
@Override
public void didSomethingAwesome() {
/* do nothing */
}
}
}
Then someone can come along and just implement the stuff they care about:
class AwesomeDelegate extends MyClassDelegateAdapter {
@Override
public void didSomethingAwesome() {
System.out.println("Yeah!");
}
}
Either that, or pure reflection calling "known" methods. But that's insane.