Guvav-EventBus

2022-03-18  本文已影响0人  63f4fe6cfa47

事件监听者[Listeners]

监听特定事件(如,CustomerChangeEvent):

把事件监听者注册到事件生产者:

按事件超类监听(如,EventObject甚至Object):

检测没有监听者的事件:

事件生产者[Producers]

管理和追踪监听者:

向监听者分发事件:

术语表

事件总线系统使用以下术语描述事件分发:

事件 可以向事件总线发布的对象
订阅 向事件总线注册监听者以接受事件的行为
监听者 提供一个处理方法,希望接受和处理事件的对象
处理方法 监听者提供的公共方法,事件总线使用该方法向监听者发送事件;该方法应该用Subscribe注解
发布消息 通过事件总线向所有匹配的监听者提供事件

例1:

定义一个监听者:

public class SimpleListener {

    @Subscribe
    public void action(final String event){
        System.out.println("action方法被执行了,接收到参数["+ event +"]");
    }
}

定义一个生产者

public class SimpleEventBusExample {
    public static void main(String[] args) {
        EventBus eventBus = new EventBus();
        //指定执行的监听者
        eventBus.register(new SimpleListener());
        eventBus.post("测试");
    }
}

结果:

action方法被执行了,接收到参数[测试]

例2:如果一个类里面有两个监听者,但是参数不一样(基本类型参数需要使用包装类型)

定义两个参数类型不同的监听者

public class SimpleListener {

    @Subscribe
    public void action1(final String event){
        System.out.println("action1方法被执行了,接收到参数["+ event +"]");
    }

    @Subscribe
    public void action2(final Integer event){
        System.out.println("action2方法被执行了,接收到参数["+ event +"]");
    }
}

定义一个生产者

public class SimpleEventBusExample {
    public static void main(String[] args) {
        EventBus eventBus = new EventBus();
        eventBus.register(new SimpleListener());
        eventBus.post("测试");
        eventBus.post("1");
    }
}

结果

action1方法被执行了,接收到参数[测试]
action1方法被执行了,接收到参数[1]

例2:如果子类和父类都有监听方法,指定子类监听时,父类的监听方法也会被执行

定义一个子类和一个父类,都各自有一个监听方法

//父类
public abstract class AbstractListener {

    @Subscribe
    public void action(String event){
        System.out.println("抽象类action方法被执行了,接收到参数["+ event +"]");
    }
}

//子类
public class CreateListener extends AbstractListener{

    @Subscribe
    public void actionSon(String event){
        System.out.println("子类actionSon方法被执行了,接收到参数["+ event +"]");
    }
}

定义一个生产者

public class SimpleEventBusExample {
    public static void main(String[] args) {
        EventBus eventBus = new EventBus();
        eventBus.register(new CreateListener());
        eventBus.post("测试");
    }
}

结果:

子类actionSon方法被执行了,接收到参数[测试]
抽象类action方法被执行了,接收到参数[测试]
上一篇 下一篇

猜你喜欢

热点阅读