java eventbus
时间: 2023-11-20 16:53:39 浏览: 86
eventBus.jar
Java Event Bus是一种用于处理事件的设计模式,它允许不同组件之间的松散耦合通信。它基于发布/订阅模型,其中事件被发布到事件总线,然后订阅该事件的所有组件都会收到该事件。以下是Java Event Bus的一些用法和示例:
```java
// 定义事件类
public class MyEvent {
private String message;
public MyEvent(String message) {
this.message = message; }
public String getMessage() {
return message;
}
}
// 定义订阅者类
public class MySubscriber {
@Subscribe
public void onEvent(MyEvent event) {
System.out.println("Received event with message: " + event.getMessage());
}
}
// 创建事件总线并注册订阅者
EventBus eventBus = new EventBus();
MySubscriber subscriber = new MySubscriber();eventBus.register(subscriber);
// 发布事件
eventBus.post(new MyEvent("Hello, world!"));
// 输出:Received event with message: Hello, world!
```
阅读全文