观察者模式和EventBus

观察者模式和EventBus

在熟悉一些项目的时候,发现项目中的一些设计模式,之后会慢慢写。这里就写项目中的观察者的使用。

观察者模式在被观察者和观察者之间建立一个抽象的耦合。被观察者角色所知道的只是一个具体观察者列表,每一个具体观察者都符合一个抽象观察者的接口。被观察者并不认识任何一个具体观察者,它只知道它们都有一个共同的接口。

关于观察者模式,之前写过见 https://blog.csdn.net/qq_23934475/article/details/83094462

这里介绍一下EventBus的使用

消息定义

@Data
@Builder
public class Message {

    private String name;

    private String content;

    private Type type;

    @AllArgsConstructor
    public enum Type{
        CREATE(1,"create data"),
        READ(1,"read data"),
        UPDATE(1,"update"),
        DELETE(1,"delete data");

        @Getter
        private Integer value;
        @Getter
        private String describe;

    }
}

消息分发

public class Dispatcher {

    private EventBus eventBus = new EventBus();

    private Subscriber subscriber = new Subscriber();

    {
        eventBus.register(subscriber);
    }

    public void dispatcher(Message message){
        eventBus.post(message);
    }

}

消息接收并处理

public class Subscriber {

    @Subscribe
    public void create(Message message) {
      if (Message.Type.CREATE.equals(message.getType())){
        System.out.println(MessageFormat.format("the create  message is {0}", message));
      }
    }

  @Subscribe
  public void update(Message message) {
      if (Message.Type.UPDATE.equals(message.getType())){
        System.out.println(MessageFormat.format("the update  message is {0}", message));
      }
  }
}

测试

public class DispatcherTest {

  private Dispatcher dispatcher = new Dispatcher();
  private Message create;
  private Message update;
  @Before
  public void init(){
    create = Message.builder().name("hello").content("world").type(Message.Type.CREATE).build();
    update = Message.builder().name("hello").content("world").type(Message.Type.UPDATE).build();

  }

  /**
   * Output: the create  message is Message(name=hello, content=world, type=CREATE)
   */
  @Test
  public void createMessageTest(){
    dispatcher.dispatcher(create);
  }

  /**
   * Output: the update  message is Message(name=hello, content=world, type=UPDATE)
   */
  @Test
  public void updateMessageTest(){
    dispatcher.dispatcher(update);
  }
}

具体见Demo源码见 https://github.com/googalAmbition/googol

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tcoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值