SpringBoot中实现简单观察者模式

观察者模式介绍

观察者模式介绍:当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者模式属于行为型模式

观察者模式是发布订阅模式的一种特殊实现,发布订阅模式是在观察者模式的基础上做的优化升级

观察者模式Java版本简单实现参考链接:https://www.runoob.com/design-pattern/observer-pattern.html

SpringBoot实现

注意:此处业务场景为用户购买商品下单并增加对应购物积分


1.创建Event事件类

ShoppingEvent事件类

public class ShoppingEvent extends ApplicationEvent {

    /**
     * 调用祖先类构造 传入一个user对象
     */
    private ShoppingEvent(User user) {
        super(user);
    }

    /**
     * 创建一个Event对象
     */
    public static ShoppingEvent buildEvent(User user) {
        return new ShoppingEvent(user);
    }

}

ShoppingEvent的祖先类为EventObject源码如下

实际上就是一个构造方法、getSource和toString方法,当构造器传入对象为null时会抛出异常

public class EventObject implements java.io.Serializable {

    @java.io.Serial
    private static final long serialVersionUID = 5516075349620653480L;

    /**
     * The object on which the Event initially occurred.
     */
    protected transient Object source;

    /**
     * Constructs a prototypical Event.
     *
     * @param source the object on which the Event initially occurred
     * @throws IllegalArgumentException if source is null
     */
    public EventObject(Object source) {
        if (source == null)
            throw new IllegalArgumentException("null source");

        this.source = source;
    }

    /**
     * The object on which the Event initially occurred.
     *
     * @return the object on which the Event initially occurred
     */
    public Object getSource() {
        return source;
    }

    /**
     * Returns a String representation of this EventObject.
     *
     * @return a String representation of this EventObject
     */
    public String toString() {
        return getClass().getName() + "[source=" + source + "]";
    }
}

2.创建EventListener监听器

实现方法一: 创建监听器

ShoppingListener监听器类

注意:实现接口的泛型为自定义事件ShoppingEvent,代表这个监听器监听这个事件

@Component
public class ShoppingListener implements ApplicationListener<ShoppingEvent> {

    /**
     * 若事件发布则执行该方法
     */
    @Override
    public void onApplicationEvent(ShoppingEvent event) {
        User user = (User) event.getSource();
        System.out.println("用户" + user.getId() + "增加积分");
    }

}

接口ApplicationListener源码如下,父类EventListener为空接口

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    void onApplicationEvent(E event);

    /**
     * Spring框架使用
     */
    static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
        return (event) -> {
            consumer.accept(event.getPayload());
        };
    }
}
实现方法二: @EventListener注解

注意: 注解方式基于反射实现,方法入参为需要监听的事件

@Service
public class SendMsgServiceImpl implements SendMsgService {

    /**
     * 当用户购买商品则发送消息
     */
    @EventListener
    public void sendMessagesWhenShopping(ShoppingEvent event) {
        User user = (User) event.getSource();
        System.out.println("用户" + user.getId() + "成功发送信息");
    }

}

3.创建Service发布事件

此处注入ApplicationContext来发布对应事件,SpringBoot会通知对应的监听器去执行对应的事件

@Service
public class ShoppingServiceImpl implements ShoppingService {

    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private LoginService loginService;

    @Override
    public String calcPrice(String price) {
        // 获取当前登录用户
        User loginUser = loginService.getLoginUser();

        // 主要业务 例如创建保存订单等...

        // 次要弱依赖业务 此处采用发布事件异步触发增加积分事件
        applicationContext.publishEvent(ShoppingEvent.buildEvent(loginUser));
        return "success";
    }

}

4.创建单元测试

@SpringBootTest
class SpringbootApplicationTests {

    @Resource
    private ShoppingService shoppingService;

    @Test
    void contextLoads() {
        String result = shoppingService.calcPrice("56");
        System.out.println("result = " + result);
    }

}

执行单元测试得到结果

用户123增加积分
result = success

至此我们通过SpringBoot实现了观察者模式,其中的通知监听器执行对应事件的操作SpringBoot代我们做了,有兴趣的可以去研究一下对应的源码,本文主打实现,不再过多赘述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Spring Boot观察者模式被广泛应用于事件驱动的编程模型。Spring Boot通过使用事件和监听器来实现观察者模式,以实现对象之间的解耦和通信。 在Spring Boot,事件是一个特殊的对象,它封装了与应用程序相关的状态信息。当某个特定的事件发生时,Spring Boot会自动通知所有注册的监听器,并将事件对象传递给它们。监听器可以根据事件的类型和内容来执行相应的操作。 下面是一个简单的示例,演示了如何在Spring Boot使用观察者模式: 1. 创建一个事件类,例如`MyEvent`,用于封装事件的相关信息。 2. 创建一个监听器类,例如`MyEventListener`,实现`ApplicationListener`接口,并指定要监听的事件类型。 ```java import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class MyEventListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { // 处理事件 System.out.println("Received event: " + event.getMessage()); } } ``` 3. 在需要触发事件的地方,使用`ApplicationEventPublisher`接口的实现类来发布事件。 ```java import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; @Component public class MyEventPublisher { private final ApplicationEventPublisher eventPublisher; public MyEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } public void publishEvent(String message) { // 创建事件对象 MyEvent event = new MyEvent(message); // 发布事件 eventPublisher.publishEvent(event); } } ``` 通过以上步骤,我们就可以在Spring Boot使用观察者模式了。当`MyEventPublisher`发布事件时,`MyEventListener`会自动接收到事件并执行相应的操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一只嘻嘻嘻

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

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

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

打赏作者

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

抵扣说明:

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

余额充值