interface MyInterface {
void sayHello();
}
class MyImpl implements MyInterface {
@Override
public void sayHello() {
System.out.println("Hello");
}
}
class MyDelegate {
private final MyInterface impl;
public MyDelegate(MyInterface i) {
this.impl = i;
}
public void execDelegate() {
impl.sayHello();
}
}
// 呼び出し側の例
class Main {
public static void main(String[] args) {
MyImpl impl = new MyImpl();
MyDelegate delegate = new MyDelegate(impl);
delegate.execDelegate(); // -> "Hello"
}
}
delegate void MyDelegate();
class MyImpl {
public void method() {
Console.Write("Hello");
}
}
class MainClass {
static void Main(String[] args) {
MyImpl impl = new MyImpl();
MyDelegate del = new MyDelegate(impl.method);
del(); // -> "Hello"
}
}
Javaではメソッドを引数として渡したりすることは(リフレクションを使わない限りは)できないので、interfaceを使いました。
こう考えると、C#はよりシンプルなコードでdelegate(委譲)を実装できるのかなと思います。