guava eventbus demo

事件总线模式基于发布订阅模式,能够方便将副业务功能从主业务功能中脱离,在主业务逻辑上,只需要post事件,其他逻辑将在事件中执行

1、使用注解方式

@Subscribe将监听方法注册到总线上,当总线post event时,所有该event事件的方法都会得到执行

public class EventBusTest {
public static void main(String[] args) {
EventBus eventBus= new EventBus();
EventAuditor eventAuditor=new EventAuditor( eventBus);
eventBus.post(new praiseEvent());//子类事件
eventBus.post(new CommentEvent());//子类事件

}
}

public class EventAuditor   {
List<BaseEvent> sellEvents = Lists.newArrayList();
public EventAuditor(EventBus eventBus){
eventBus.register(this);//该类注册到总线
}
@Subscribe
public void lister(BaseEvent baseEvent) {
sellEvents.add(baseEvent);
System.out.printf("%s from %n", baseEvent.praise());
}
public List<BaseEvent> getSellEvents() {
return sellEvents;
}
}

具体事件
public class CommentEvent implements BaseEvent {
@Override
public String praise() {
return "commentevent";
}
}

2、维护一个列表,用于保存事件监听;每次将事件注册到监听器中,当post相应事件时,通过instanceOf判断具体事件,执行具体事件的逻辑。
 

转载于:https://www.cnblogs.com/cindy-zhu/p/7009553.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值