栗子
代码语言:txt复制public class TestPreconditions {
static class Listener {
@Subscribe
public void listen(String eventData) {
System.out.println("接收到事件数据:" eventData);
}
@Subscribe
public void listen(Integer eventData) {
System.out.println("接收到事件int数据:" eventData);
}
}
public static void main(String[] args) {
EventBus bus = new EventBus();
bus.register(new Listener());
bus.post("这是事件数据!");
bus.post(123456);
}
}
结果:
应用场景
我们假设你需要设计一个lol里面各种英雄获得buff的处理,你就可以采用如下代码
代码语言:txt复制public class TestLolBuff {
//蓝buff
static class BlueBuff {
}
//红buff
static class RedBuff {
}
//小龙buff
static class DragonetBuff {
}
//大龙buff
static class BaronBuff {
}
static class Listener {
@Subscribe
public void listen(BlueBuff eventData) {
System.out.println("我得到了蓝buff:");
}
@Subscribe
public void listen(RedBuff eventData) {
System.out.println("我得到了红buff:");
}
@Subscribe
public void listen(DragonetBuff eventData) {
System.out.println("我得到了小龙buff:");
}
@Subscribe
public void listen(BaronBuff eventData) {
System.out.println("我得到了大龙buff:");
}
}
public static void main(String[] args) {
EventBus bus = new EventBus();
bus.register(new Listener());
bus.post(new DragonetBuff());
}
}
输出:
异步
代码语言:txt复制public static void main(String[] args) {
AsyncEventBus bus = new AsyncEventBus();
bus.register(new Listener());
bus.post(new DragonetBuff());
}
与Spring结合使用
每次都new AsyncEventBus();这种方式为免有点太low,可以使用@Bean
注解构建一个Bean对象
@Component
public class AsyncEventBusBean {
@Bean
public AsyncEventBus asyncEventBus() {
AsyncEventBus eventBus = new AsyncEventBus(Executors.newFixedThreadPool(10));
eventBus.register(new xxx());
return eventBus;
}
}
代码语言:txt复制@Autowired
private AsyncEventBus asyncEventBus;
asyncEventBus.post(xxx);