观察者模式在Java单体服务中的运用

发布于:2025-04-04 ⋅ 阅读:(34) ⋅ 点赞:(0)

观察者模式主要用于当一个对象发生改变时,其关联的所有对象都会收到通知,属于事件驱动类型的设计模式,可以对事件进行监听和响应。下面简单介绍下它的使用:

1 定义事件

import org.springframework.context.ApplicationEvent;

public class OrderCreatedEvent extends ApplicationEvent {
    private final Long orderId;

    public OrderCreatedEvent(Object source, Long orderId) {
        super(source);
        this.orderId = orderId;
    }

    public Long getOrderId() {
        return orderId;
    }
}

2 事件发布者

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
    private final ApplicationEventPublisher eventPublisher;

    public OrderService(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    public void createOrder(Long orderId) {
        // 创建订单逻辑
        System.out.println("订单创建成功: " + orderId);

        // 发布事件
        eventPublisher.publishEvent(new OrderCreatedEvent(this, orderId));
    }
}

3 事件监听者

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class NotificationService {

    @EventListener
    public void handleOrderCreated(OrderCreatedEvent event) {
        System.out.println("发送通知:订单 " + event.getOrderId() + " 创建成功!");
    }
}

注意事项:观察者模式只能在同一个微服务中使用,跨服务中将失效。