学习Spring必须了解的基础知识——回调机制

上面这张图如果能看得懂就能理解什么是回调机制:

        A对象在调用a()方法时会调用B对象的b()方法,b()方法必须能调用A对象的callback()方法。

谁白了:a()方法有B对象b()方法的引用,b()方法有对a对象中callback()的引用。

package priv.lirenhe.callback;


public interface CallBack {

public void claimAnswer(String answer); 


}
package priv.lirenhe.callback;


public interface TeacherA {

public void askQuestion(StudentB student);


}
package priv.lirenhe.callback;


public class TeacherAImpl implements CallBack,TeacherA{//实现CallBack类从而实现claimAnswer方法


public TeacherAImpl() {
// TODO Auto-generated constructor stub
}


@Override
public void claimAnswer(String answer) {
System.out.println("该同学的答案是:"+answer);

}


@Override
public void askQuestion(StudentB student){//有对对象B的引用
student.resolveQues(this);
}



}
package priv.lirenhe.callback;


public interface StudentB {


public String resolveQues(CallBack callBack);


}
package priv.lirenhe.callback;


public class StudentBImpl implements StudentB {


public StudentBImpl() {
// TODO Auto-generated constructor stub
}


@Override
public String resolveQues(CallBack callBack) {//有CallBack对象的应用
String answer = "你去死";
callBack.claimAnswer(answer);
return answer;
}


}
package priv.lirenhe.callback;


public class TestCallBack {


public TestCallBack() {
// TODO Auto-generated constructor stub
}


public static void main(String[] args) {
StudentBImpl studentB = new StudentBImpl();
TeacherAImpl teacherA = new TeacherAImpl();
teacherA.askQuestion(studentB);
}
}


posted @ 2018-07-01 12:33  西装人  阅读(1315)  评论(0编辑  收藏  举报