一目了然,也不用多说了,随便记录下,内部实现基于观察者模式
TestEvent
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; } }
EventListener 也可以多个subscribe,根据参数进入每个方法
import com.google.common.eventbus.Subscribe; 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; } }
TestEventBus
import com.google.common.eventbus.EventBus; public class TestEventBus { public static void main(String[] args) 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()); ; } }
打印结果
event message:200 Message:200 event message:300 Message:300 event message:400 Message:400 LastMessage:400