Guava事件总线-EventBus

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

EventBus基本用法:

  使用Guava之后, 如果要订阅消息, 就不用再继承指定的接口, 只需要在指定的方法上加上@Subscribe注解即可。

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.junit.Test;

/**
 * @author Kevin
 * @description
 * @date 2016/8/5
 */
public class EventBusTest {
    @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());
    }
}

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;
    }
}

class TestEvent {
    int message;

    public TestEvent(int message) {
        this.message = message;
    }

    public int getMessage() {
        return message;
    }

    public void setMessage(int message) {
        this.message = message;
    }
}

多listener与event继承的示例

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.junit.Test;

/**
 * @author Kevin
 * @description
 * @date 2016/8/5
 */
public class MultiEventBusTest {

    @Test
    public void multiEventBusTest() {
        EventBus eventBus = new EventBus("multiEventListener");
        eventBus.register(new MultiEventListener());

        eventBus.post(100);
        eventBus.post(200L);
        eventBus.post("Kevin");
    }
}

class MultiEventListener {
    // Number是Integer和Long的父类,可以收到事件
    @Subscribe
    public void numberEvent(Number event) {
        System.out.println("numbereger event = " + event);
    }

    @Subscribe
    public void integerEvent(Integer event) {
        System.out.println("integer event = " + event);
    }

    @Subscribe
    public void longEvent(Long event) {
        System.out.println("long event = " + event);
    }

    @Subscribe
    public void stringEvent(String event){
        System.out.println("String event = " + event);
    }
}

 

转载于:https://my.oschina.net/kevinair/blog/727975

你可能感兴趣的:(javascript,python)