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)