美文网首页
Guava 中的事件总线

Guava 中的事件总线

作者: hemiao3000 | 来源:发表于2020-04-25 22:07 被阅读0次

    本片内容收录在我的在线笔记 java-note-for-free 中。

    笔记源文件在 gitee 中。

    EventBus 是 Guava 的事件处理机制,是设计模式中的观察者模式(生产/消费者编程模型)的优雅实现。对于事件监听和发布订阅模式,EventBus 是一个非常优雅和简单解决方案,我们不用创建复杂的类和接口层次结构。

    使用 EventBus 需要做三方面的工作:

    自定义 Event

    在最简单的情况下,这一步并不是必须的。因为 Guava 的 EventBus 机制不像其它的库的 EventBus 那样要求必须实现某个接口(或继承某个类)。Guava 的 EventBus 允许任意的类型作为 Event 对象。因此你完全可以使用 String 作为 Event 对象。

    public class HelloCommand {
    
        public HelloCommand() {
        }
    
    }
    

    定义 EventHandler

    和定义 Event 一样,Guava 不强求你的自定义类必须实现某个接口(或继承某个类)。

    public class HelloCommandHandler {
    
        @Subscribe
        public void handle(HelloCommand command) {
            System.out.println("触发执行");
        }
    }
    

    这里需要注意的有两点:

    1. Guava 不强求定义的 EventHandler 必须实现某个接口。所以,我们要通过 @Subscribe 在 EventHandler 中的众多方法中标识出哪个方法是事件处理方法。

    2. 逻辑上,EventHandler 的事件处理方法的参数应该是它所能处理的 Event 对象。

    注册 EventHandler

    你需要在一个合适的地方创建一个 EventBus 对象,并在合适的地方通过它注册你的 EventHandler 。

    EventBus eventBus = new EventBus("Joker");
    eventBus.register(new HelloCommandHandler());
    

    触发事件

    eventBus.post(new HelloCommand());
    

    相关文章

      网友评论

          本文标题:Guava 中的事件总线

          本文链接:https://www.haomeiwen.com/subject/bamlwhtx.html