1,場(chǎng)景:模擬教師給學(xué)生布置作業(yè),學(xué)生完成后將結(jié)果回告教師
2,初始化學(xué)生類:
public class Student {
/*
回調(diào)實(shí)際上是調(diào)用方Teacher將自身的實(shí)例teacher(Teacher.this)傳遞給被調(diào)用方Student對(duì)應(yīng)的方法
doHomeWork(WcsCallBack wcsCallBack, String task)內(nèi)。
*/
public void doHomeWork(WcsCallBack wcsCallBack, String task) throws InterruptedException {
System.out.println("接到老師的作業(yè):"+task);
System.out.println("學(xué)生正在做作業(yè)");
Thread.sleep(1000);
System.out.println("作業(yè)已經(jīng)完成");
String result="【Today's homeWorker is so easy】";
wcsCallBack.complete("notify Teacher the result of Today's homeWorker"+result);
}
}
3,設(shè)置回調(diào)方法。(此方法被Student中使用)
public interface WcsCallBack {
public void complete(String result);
}
4,初始化Teacher類
public class Teacher implements WcsCallBack {
private Student student;
public Teacher(Student student) {
this.student = student;
}
/*
下發(fā)布置作業(yè)
*/
public void commandMethod(String homeWorker ){
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("即將布置作業(yè)...");
try {
/*
doHomeWork(WcsCallBack wcsCallBack, String task)。
Teacher類實(shí)現(xiàn)了WcsCallBack接口,所以可以作為WcsCallBack實(shí)例傳入。
/*
回調(diào)實(shí)際上是調(diào)用方Teacher將自身的實(shí)例teacher(Teacher.this)傳遞給被調(diào)用方Student對(duì)應(yīng)的方法
doHomeWork(WcsCallBack wcsCallBack, String task)內(nèi)。
*/
student.doHomeWork(Teacher.this,homeWorker);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void complete(String result) {
System.out.println("收到學(xué)生對(duì)于今天作業(yè)的反饋:"+result);
}
5,寫測(cè)試類:
public class TestClass {
public static void main(String[] args){
Student stu = new Student();
Teacher teacher = new Teacher(stu);
System.out.println("進(jìn)入測(cè)試程序");
String homeWorker="【萬(wàn)歷十五年朗讀第三章】";
teacher.commandMethod(homeWorker);
}
}
6,結(jié)果輸出:
進(jìn)入測(cè)試程序
即將布置作業(yè)...
接到老師的作業(yè):【萬(wàn)歷十五年朗讀第三章】
學(xué)生正在做作業(yè)
作業(yè)已經(jīng)完成
收到學(xué)生對(duì)于今天作業(yè)的反饋:notify Teacher the result of Today's homeWorker【Today's homeWorker is so easy】