6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#のDelegateをJava的に考えてみる

Last updated at Posted at 2015-06-05
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(委譲)を実装できるのかなと思います。

6
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?