事件回调

事件回调其实是一种常见的设计模式, 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值