Write C# delegate in java

送分小仙女□ 提交于 2020-01-23 19:08:00

问题


How can I write code below in java version?

I have read similar questions, but they are confusing, they answered that java didn't have delegate feature like c# had, in other hand they answered with their delegate implementation in java, but nothing is similar with my condition. I really hope it's clear on this question. I have been getting stuck since a week

    class Action
    {
        public delegate void ActionDelegate();
        public static ActionDelegate OnAction;

        public void DoAction()
        {
            Console.WriteLine("Action A");
            if (!ReferenceEquals(OnAction, null))
                OnAction();
        }
    }
    class TaskA
    {
        public TaskA()
        {
            Action.OnAction += DoTaskA;
        }
        private void DoTaskA()
        {
            Console.WriteLine("Do Task A");
        }

    }
    class TaskB
    {
        public TaskB()
        {
            Action.OnAction += DoTaskB;
        }
        private void DoTaskB()
        {
            Console.WriteLine("Do Task B");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            TaskA taskA = new TaskA();
            TaskB task = new TaskB();
            Action action = new Action();
            action.DoAction();
        }
    }

Output:

Action A
Do Task A
Do Task B
Press any keys to continue...

回答1:


something similar in java will be to use an interface

you can get the following results

Action A
Do Task A
Do Task B

with the codes below.

import java.util.ArrayList;
public class HelloWorld{

     public static void main(String []args){ 

            TaskA taskA = new TaskA();
            TaskB task = new TaskB();
            Action action = new Action();
            action.doAction();
     }
}

interface ActionDelegate {
    void doAction();
}

class Action{

    static public ArrayList<ActionDelegate> onAction = new ArrayList<>();
    public void doAction(){
        System.out.println("Action A");
        for(ActionDelegate ad: onAction){
            ad.doAction();
        }
    }
}
class TaskA implements ActionDelegate{

    TaskA(){
        Action.onAction.add(this);
    }
    public void doAction(){ 
            System.out.println("Do Task A");
    }

}

class TaskB implements ActionDelegate{

    TaskB(){
        Action.onAction.add(this);
    }
    public void doAction(){ 
            System.out.println("Do Task B");
    }

}


来源:https://stackoverflow.com/questions/59606165/write-c-sharp-delegate-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!