Java 回调函数机制与实现

基本步骤

  1. 写出一个接口类CallBack,该接口有一个方法名为AFunction, AFunction 即为class B回调时候使用的方法
  2. 写一个class A实现接口CallBack,即A中应该重写了AFunction
  3. class A中有一个方法 BFunction ,其中一个参数为class B的引用b,该方法中调用了calss B的一个方法 CFunction
  4. class B有一个参数为callback的方法 CFunction (CallBack callback),在该方法中使用callback. AFunction ()完成回调
  5. 实例化一个对象A,实例化一个对象B,调用A的 BFunction 方法将B作为参数传入,

以下代码中,doHomeWork接口是CallBack接口,finishHomeWork是AFunction,student类为class A,doHomeworkByRommate是 BFunction ,roommate类为class B, DoStudentHomeWork为CFunction

doHomeWork.java

package a;

public interface doHomeWork
{
    void finishHomeWork(String answer);
}

student.java

package a;

public class student implements doHomeWork{
    public void doHomeworkByRommate(String question,roommate b)
    {
        b.DoStudentHomeWork(question,this);
    }

    @Override
    public void finishHomeWork(String answer) {
        System.out.print("done.answer is "+answer);
    }
}

roommate.java

package a;

public class roommate{
    public void DoStudentHomeWork(String question,doHomeWork student)
    {
        String answer="aaa";
        student.finishHomeWork(answer);
    }
}

main.java

package a;

public class Main {

    public static void main(String[] args) {
        student a=new student();
        roommate b=new roommate();
        a.doHomeworkByRommate("question",b);
    }
}

运行结果:

done.answer is aaa

发表评论