「Java」デリゲート(delegate)を利用するサンプル

環境
JDK1.8
Eclipse2019

説明
委譲(デリゲート)はメソッドを実行するとき、他のクラスのメソッドを利用します。
他のクラスのメソッドを使用するので、同じメソッドを実装しなくてよくなります。

使用例
1.処理を記述するクラスの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class TestA {
//処理を記述したクラス
public void funA() {
System.out.println("委譲テスト123456");
}
}
package com.arkgame.study; public class TestA { //処理を記述したクラス public void funA() { System.out.println("委譲テスト123456"); } }
package com.arkgame.study;

public class TestA {

      //処理を記述したクラス
      public void funA() {
            System.out.println("委譲テスト123456");
      }
}

2.委譲しているクラスの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class TestB {
//TestAクラスのインスタンスを生成
TestA uu = new TestA();
//委譲クラス
public void funA() {
uu.funA();
}
}
package com.arkgame.study; public class TestB { //TestAクラスのインスタンスを生成 TestA uu = new TestA(); //委譲クラス public void funA() { uu.funA(); } }
package com.arkgame.study;

public class TestB {
      
      //TestAクラスのインスタンスを生成
      TestA uu = new TestA();
      
      //委譲クラス
      public void  funA() {
            uu.funA();
      }
}

3.処理を実行しているクラス

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
//処理実行クラス
public class TestDemo {
public static void main(String[] args) {
//TestBクラスのインスタンスを生成
TestB ub = new TestB();
//TestAクラスのメソッドを実行
ub.funA();
}
}
package com.arkgame.study; //処理実行クラス public class TestDemo { public static void main(String[] args) { //TestBクラスのインスタンスを生成 TestB ub = new TestB(); //TestAクラスのメソッドを実行 ub.funA(); } }
package com.arkgame.study;

//処理実行クラス
public class TestDemo {

      public static void main(String[] args) {
            //TestBクラスのインスタンスを生成
            TestB ub = new TestB();
            //TestAクラスのメソッドを実行
            ub.funA();
      }

}

実行結果
委譲テスト123456

Java

Posted by arkgame