EventBus是Guava框架对观察者模式的一种实现,使用EventBus可以很简洁的实现事件注册监听和消费。Guava框架里面提供了两种相关的实现,一种是单线程同步事件消费,另外一直是多线程异步事件消费。后者在对象设计上是前者的子类。
eventBus 是通过传递的参数来决定具体调用那个订阅者方法,
1.两个简短的观察者类
public class DataObserver1 {
/**
* 只有通过@Subscribe注解的方法才会被注册进EventBus
* 而且方法有且只能有1个参数
*
* @param msg
*/
@Subscribe
public void func(String msg) throws InterruptedException {
Thread.sleep(1000);
System.out.println("String msg: " + msg);
}
}
public class DataObserver2 {
/**
* post() 不支持自动装箱功能,只能使用Integer,不能使用int,否则handlersByType的Class会是int而不是Intege
* 而传入的int msg参数在post(int msg)的时候会被包装成Integer,导致无法匹配到
*/
@Subscribe
public void func(Integer msg) {
try {
// Thread.sleep(3000); 为了测试异步
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Integer msg: " + msg);
}
}
一般不支持这样一上来就创建eventBus 对象实例,这里为了方便
public class EventBusCenter {
private static EventBus eventBus = new EventBus();
private EventBusCenter() {
}
public static EventBus getInstance() {
return eventBus;
}
public static void register(Object obj) {
eventBus.register(obj);
}
public static void unregister(Object obj) {
eventBus.unregister(obj);
}
public static void post(Object obj) {
eventBus.post(obj);
}
}
来,简单的测试一下
public static void main(String[] args) throws InterruptedException {
DataObserver1 observer1 = new DataObserver1();
DataObserver2 observer2 = new DataObserver2();
DataObserver3 observer3 = new DataObserver3();
EventBusCenter.register(observer1);
EventBusCenter.register(observer2);
EventBusCenter.register(observer3);
System.out.println("============ start ====================");
// 只有注册的参数类型为String的方法会被调用
EventBusCenter.post("post string method");
EventBusCenter.post(123);
System.out.println("============ after unregister ============");
// 注销observer2
EventBusCenter.unregister(observer2);
EventBusCenter.post("post string method");
EventBusCenter.post(123);
System.out.println("============ end =============");
}
EventBus 还提供了异步调用,也就是多线程,
DataObserver1 和 DataObserver2 中的sleep 就是为了测试异步简单看一下代码,
public class TestAseyEvbenBus {
private static AsyncEventBus asyncEventBus;
public static void main(String[] args) {
asyncEventBus = new AsyncEventBus(Executors.newFixedThreadPool(100));
DataObserver1 observer1 = new DataObserver1();
DataObserver2 observer2 = new DataObserver2();
DataObserver3 dataObserver3 = new DataObserver3();
asyncEventBus.register(dataObserver3);
asyncEventBus.register(observer1);
asyncEventBus.register(observer2);
asyncEventBus.post(11111);
asyncEventBus.post(1231L);
asyncEventBus.post("hello event");
System.out.println("异步调用 ");
}
}
好了,这里简单做了一个应用,同步和异步调用;