import org.junit.Test;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
public class TestEventBus {
public class TestEvent {
private final int message;
public TestEvent(int message) {
this.message = message;
System.out.println("event message:"+message);
}
public int getMessage() {
return message;
}
}
public class EventListener {
public int lastMessage = 0;
@Subscribe
public void listen(TestEvent event) {
lastMessage = event.getMessage();
System.out.println("Message:"+lastMessage);
}
public int getLastMessage() {
return lastMessage;
}
}
@Test
public void testReceiveEvent() throws Exception {
EventBus eventBus = new EventBus("test");
EventListener listener = new EventListener();
eventBus.register(listener);
eventBus.post(new TestEvent(200));
eventBus.post(new TestEvent(300));
eventBus.post(new TestEvent(400));
System.out.println("LastMessage:"+listener.getLastMessage());
eventBus.unregister(listener);
eventBus.post(new TestEvent(500));
System.out.println("LastMessage:"+listener.getLastMessage());
}
}
guava优雅的观察者模式
最新推荐文章于 2024-06-15 23:12:29 发布