java回调机制(同步回调)

场景:父亲问姐姐:弟弟的作业写好了吗?

   姐姐就去问弟弟:弟弟,你作业写好了吗?

   弟弟写完作业后,告诉姐姐:姐姐,我作业写完了!

   姐姐知道后,就告诉父亲:父亲,弟弟作业写完了!

代码:

CallBack.java传递消息的接口:

package myInterfaceCallback;

public interface CallBack {

public void tell(String result);
}

Brother.java弟弟类:

package myInterfaceCallback;

import myInterfaceCallback.CallBack;

public class Brother {

public void doHomework(CallBack tellSister, String question) {
System.out.println(question);
tellSister.tell("弟弟:姐姐,我已经写完了!");
}
}

Sister.java姐姐类:

package myInterfaceCallback;

public class Sister implements CallBack{

public Brother brother;

public Sister(Brother brother) {
super();
this.brother = brother;
}

@Override
public void tell(String result) {
// TODO Auto-generated method stub
System.out.println(result);

}

public void toAskBrother(CallBack tellParent, String question) {
// TODO Auto-generated method stub
brother.doHomework(Sister.this, question);
tellParent.tell("姐姐:父亲,弟弟作业写完了!");
}
}

Parent.java父亲类:

package myInterfaceCallback;

public class Parent implements CallBack{

public Sister sister;

public Parent(Sister sister) {
super();
this.sister = sister;
}

@Override
public void tell(String result) {
// TODO Auto-generated method stub
System.out.println(result);
}

public void askToSister(String question) {
// TODO Auto-generated method stub
System.out.println(question);
sister.toAskBrother(Parent.this, "姐姐:弟弟,你作业做好了吗?");
}

}

Test.java测试运行类:

package myInterfaceCallback;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub

Parent parent = new Parent(new Sister(new Brother()));

parent.askToSister("父亲:弟弟作业做好了吗?");
}

}

 运行结果:

父亲:弟弟作业做好了吗?
姐姐:弟弟,你作业做好了吗?
弟弟:姐姐,我已经写完了!
姐姐:父亲,弟弟作业写完了!

posted on 2018-07-12 23:53  zhengbiyu  阅读(305)  评论(0编辑  收藏  举报