eventbus是Google Guava的事件订阅-发布组件。其特点是简单易用,需要编写的代码量很小,也不需要继承。
<dependencies> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>20.0</version> </dependency> </dependencies>
google eventbus并没有强制要求使用单例的EventBus,而是可以自行创建,你可以在一个容器内拥有多个EventBus实例,当然也可以自行将其配置为单例。下面的代码是将EventBus配置成单例的
package study.yan.google.eventbus.demo; import com.google.common.eventbus.EventBus; public class EventBusCenter { private static EventBus eventBus = new EventBus(); private EventBusCenter() { } public static EventBus getInstance(){ return eventBus; } public static void register(Object object){ eventBus.register(object); } public static void unregister(Object object){ eventBus.unregister(object); } public static void post(Object object){ eventBus.post(object); } }
只需要在类的方法上加上@Subscribe注解即可
package study.yan.google.eventbus.demo; import com.google.common.eventbus.Subscribe; public class AdviceObserver1 { @Subscribe public void ff1(AdviceObserverEventArgs args) { System.out.println("ff2:" + args); } }
package study.yan.google.eventbus.demo; import com.google.common.eventbus.Subscribe; public class AdviceObserver2 { @Subscribe public void ff1(AdviceObserverEventArgs args) { System.out.println("ff1:" + args); } }
调用eventBus的post方法来发布一个事件
package study.yan.google.eventbus.demo; public class Program { public static void main(String[] args) { DataObserver1 dataObserver1 = new DataObserver1(); DataObserver2 dataObserver2 = new DataObserver2(); EventBusCenter.register(dataObserver1); EventBusCenter.register(dataObserver2); EventBusCenter.post("a string"); EventBusCenter.post(1); System.out.println("=============="); EventBusCenter.unregister(dataObserver1); EventBusCenter.post("a string"); EventBusCenter.post(1); } }
原文:https://www.cnblogs.com/LTEF/p/13610285.html