zoukankan      html  css  js  c++  java
  • 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("父亲:弟弟作业做好了吗?");
    }

    }

     运行结果:

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

  • 相关阅读:
    数据结构与算法(3-4)--矩阵的压缩存储
    数据结构与算法(3-3)--队列的应用
    数据结构与算法(3-2)--栈的应用
    数据结构与算法(3-1)--栈和队列
    数据结构与算法(2)--线性表(数组和链表)
    数据结构与算法(1)--时间及空间复杂度
    python变量与地址的关系
    python高级(03)--socket编程
    python高级(02)--生成器和迭代器
    python处理http接口请求
  • 原文地址:https://www.cnblogs.com/zhengbiyu/p/9302577.html
Copyright © 2011-2022 走看看