• guava包EventBus


    EventBus是guava对观察者模式的优雅实现。

    它实际上是一个基于内存的消息队列,Event Source发送一个消息到EventBus,然后再由EventBus将消息推送到所监听的Listener。解耦了发布者和订阅者,使他们可以不互相了解。

    1. 创建Listener

    我们可以通过@Subscribe注解将任意的类的方法变为一个Listener。

    public class SimpleListener {
    
        @Subscribe
        public void doEvent(final String event){
            System.out.println("SimpleListener receive string "+event);
        }
    
        @Subscribe
        public void doEvent(final  Integer event){
            System.out.println("SimpleListener receive int "+event);
        }
    
        @Subscribe
        public void doEvent(final  Record event){
            System.out.println("SimpleListener receive record "+event);
        }
    }

    再创建一个Listener

    public class ComplexListener {
        @Subscribe
        public void doEvent(final  Record event){
            System.out.println("ComplexListener receive record "+event);
        }
    }

    2.event类型

    event既可以是java原生类型Integer,String,也可以自定义。

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Record {
        private Integer id;
        private String name;
    }

    3.注册Listener

    public class EventBusExample {
        public static void main(String[] args) {
            EventBus eventBus = new EventBus();
            eventBus.register(new SimpleListener());
            eventBus.register(new ComplexListener());
            
            eventBus.post(" a event");
            eventBus.post(1);
            eventBus.post(new Record(1, "miao"));
        }
    }

    输出:

    SimpleListener receive string  a event
    SimpleListener receive int 1
    SimpleListener receive record Record(id=1, name=miao)
    ComplexListener receive record Record(id=1, name=miao)
  • 相关阅读:
    java获取src下包的文件的路径
    Java获取日期属于当年第几周
    DIV的内容自动换行
    js验证身份证格式
    处理 WebService 中的 Map 对象
    Oracle使用row_number()函数查询时增加序号列
    SpingMVC实现集合参数(Could not instantiate bean class [java.util.List])
    利用JS实现在li中添加或删除class属性
    栈的应用之中缀表达式转后缀表达式
    栈的应用之判断括号匹配
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/15882535.html
Copyright © 2020-2023  润新知