Implementation of observer mode based on spring

Observer mode

When there is a one-to-many relationship between objects, the observer pattern (Observer Pattern) is used. For example, when an object is modified, it will automatically notify the dependent objects. The observer pattern is a behavioral pattern.
Here is mainly based on spring to implement the observer mode, not much nonsense to talk about dry goods

First we define an event

public class OrderEvent extends ApplicationEvent {
    
    

    /**
     * 观察者中的事件
     * 主要作用是传递参,让监听者感知有事件发布
     */
    public OrderEvent(Object source) {
    
    
        super(source);
    }
}

Then define an event listener

@Component
public class MsgListener implements ApplicationListener<OrderEvent> {
    
    
 	/**
     * 观察者中的监听者
     * 主要是拿到参数做对应的处理
     */
    @Override
    public void onApplicationEvent(OrderEvent orderEvent) {
    
    
        String msg= (String) orderEvent.getSource();
        System.out.println(msg);
    }
}

After that, we can happily extract the messy things in the business code

@Service
public class OrderBiz {
    
    

    @Autowired
    private ApplicationContext applicationContext;

    public void test(){
    
    
        //事件
        OrderEvent orderEvent=new OrderEvent("参数");
        //发布事件交给spring容器
        applicationContext.publishEvent(orderEvent);
    }
}

The above mainly uses the spring container to implement the observer mode, and then we will talk about how spring is implemented

SimpleApplicationEventMulticaster#multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
    
    
        ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
        Executor executor = this.getTaskExecutor();
        Iterator var5 = this.getApplicationListeners(event, type).iterator();

        while(var5.hasNext()) {
    
    
            ApplicationListener<?> listener = (ApplicationListener)var5.next();
            if (executor != null) {
    
    
                executor.execute(() -> {
    
    
                    this.invokeListener(listener, event);
                });
            } else {
    
    
                this.invokeListener(listener, event);
            }
        }

    }

The above is mainly to take out all the objects in the container that implement the ApplicationListener interface and call the doInvokeListener in the invokeListener method one by one, and this method is calling listener.onApplicationEvent(event); here we can see that it corresponds to the onApplicationEvent in the ApplicationListener that we must copy ,
In fact, the important thing for the observer is how the event is sent out and how the listener detects it.

Guess you like

Origin blog.csdn.net/cj181jie/article/details/108056352