利用 Spring 中的事件监听机制也可以轻松实现观察者模式

利用 Spring 中的事件监听机制也可以轻松实现观察者模式,观察目标也不需要维护观察者列表了,相当于发布-订阅模式,它们之间是完全解耦的,但每个观察者需要创建一个 Bean。

观察者配置代码:

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class ObserverConfiguration {

  @Bean
  public XmanEventListener readerListener1() {
    return new XmanEventListener("1");
  }

  @Bean
  public XmanEventListener readerListener2() {
    return new XmanEventListener("2");
  }

  @Bean
  public XmanEventListener readerListener3() {
    return new XmanEventListener("3");
  }

}

监听类

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationListener;

@RequiredArgsConstructor
public class XmanEventListener implements ApplicationListener<XmanEvent> {

  @NonNull
  private String name;

  private String article;

  @Override
  public void onApplicationEvent(XmanEvent event) {
    // 更新
    updateArticle(event);
  }

  private void updateArticle(XmanEvent event) {
    this.article = (String) event.getSource();
    System.out.printf("我是:%s,事件更新为:%s\n", this.name, this.article);
  }

}

自定义事件类

import lombok.Getter;
import org.springframework.context.ApplicationEvent;

@Getter
public class XmanEvent extends ApplicationEvent {

    /**
     * Create a new {@code ApplicationEvent}.
     *
     * @param source the object on which the event initially occurred or with
     *               which the event is associated (never {@code null})
     */
    public XmanEvent(Object source) {
        super(source);
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值