事件回调

事件回调其实是一种常见的设计模式, Netty 就使用了这样的设计。

这里采用一个 demo,试下如下功能:

Caller 向 Notifier 提问。
提问方式是异步,接着做其他事情。
Notifier 收到问题执行计算然后回调 Caller 告知结果。
在 Java 中利用接口来实现回调,所以需要定义一个接口:


public interface CallBackListener {
    /**
     * 回调通知函数
     * @param msg
     */
    void callBackNotify(String msg) ;
}

Caller 中调用 Notifier 执行提问,调用时将接口传递过去:


public class Caller {

    private final static Logger LOGGER = LoggerFactory.getLogger(Caller.class);

    private CallBackListener callBackListener ;

    private Notifier notifier ;

    private String question ;

    /**
     * 使用
     */
    public void call(){

        LOGGER.info("开始提问");

        //新建线程,达到异步效果 
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    notifier.execute(Caller.this,question);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        LOGGER.info("提问完毕,我去干其他事了");
    }

    //隐藏 getter/setter

}   

Notifier 收到提问,执行计算(耗时操作),最后做出响应(回调接口,告诉 Caller 结果)。


public class Notifier {
 
    private final static Logger LOGGER = LoggerFactory.getLogger(Notifier.class);

    public void execute(Caller caller, String msg) throws InterruptedException {

        LOGGER.info("收到消息=【{}】", msg);

        LOGGER.info("等待响应中。。。。。");

        TimeUnit.SECONDS.sleep(2);

        caller.getCallBackListener().callBackNotify("我在北京!");

    }

}

模拟执行:

public static void main(String[] args) {

        Notifier notifier = new Notifier() ;

        Caller caller = new Caller() ;

        caller.setNotifier(notifier) ;

        caller.setQuestion("你在哪儿!");

        caller.setCallBackListener(new CallBackListener() {

            @Override
            public void callBackNotify(String msg) {

                LOGGER.info("回复=【{}】" ,msg);
            }
        });

        caller.call();

    }public static void main(String[] args) {

        Notifier notifier = new Notifier() ;

        Caller caller = new Caller() ;

        caller.setNotifier(notifier) ;

        caller.setQuestion("你在哪儿!");
  
       caller.setCallBackListener(new CallBackListener() {
  
          @Override
            public void callBackNotify(String msg) {
   
             LOGGER.info("回复=【{}】" ,msg);
            }
        });

        caller.call();
    }

这样一个模拟的异步事件回调就完成了。

宁鸣默笙
原文地址:https://www.cnblogs.com/Solomon-xm/p/9367435.html