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("父亲:弟弟作业做好了吗?");
    }

    }

     运行结果:

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

  • 相关阅读:
    mysql数据库 详解
    0810 smarty
    抽象类
    Nginx 负载均衡策略
    Nginx 负载均衡配置和策略
    内置Web Server
    PHP运行方式
    MySQL create table 语法
    MySQL 索引的使用
    MySQL的 explain 解析
  • 原文地址:https://www.cnblogs.com/zhengbiyu/p/9302577.html
Copyright © 2011-2022 走看看