回调函数

自我记录 自我记录
回调函数概念还是比较清晰的:
A调用B中的方法,B完成该方法之后,再调用A中的某方法
举个栗子,现在有老师跟学生,老师问学生一个问题,学生回答该问题,回答完之后通知老师问题的答案是多少!

根据上面的叙述,可以这么做:
首先声明一个接口,这个接口让老师来实现,接口的目的是,当学生回答问题之后,通知老师问题已回答完毕

package com.mine.callback;

public interface Callback {

    void callback(String result);

}

接口完毕之后,让老师实现该接口

package com.mine.callback;

public class Teacher implements Callback {

    Student student;

    public Teacher(Student student) {
        this.student = student;
    }


    @Override
    public void callback(String result) {

        System.out.println("老师得到的答案是:" + result);
    }

    public void askQuestion(int i, int j) {
        System.out.println("老师的问题是:" + i + " + " + j + " = ?");
        student.ansQuestion(i, j, this);
    }

}

然后再实现学生类

package com.mine.callback;

public class Student {

    public void ansQuestion(int i, int j, Callback callback) {
        System.out.println("学生得到的问题是:" + i + " + " + j + " = ?");
        try {//问题比较难,需要思考两秒钟
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int result = i + j;
        System.out.println("学生想了两秒钟后回答!");
        //回答完毕了,再通知老师(因为老师实现了Callback接口,因此可以这么调用)
        callback.callback(result + "");
    }

}

使用测试类:

package com.mine.callback;

public class Client {
    public static void main(String[] args) {
        Student student = new Student();
        Teacher teacher = new Teacher(student);
        teacher.askQuestion(2, 3);
    }
}

最后运行得到的结果是:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值