This is the fifth day of my participation in Gwen Challenge

This article is participating in “Java Theme Month – Java Development in Action”, see the activity link for details

Now let’s see what observer mode is.

A. Observer B. Observer C. Observer D. Observer

Intent: Define a one-to-many dependency between objects so that when an object’s state changes, all dependent objects are notified and automatically updated.

How to understand?

When an object’s state changes, all objects that depend on it can be notified and change their state based on the notification

The above first

Xiao Ming and Xiao Xue both went to the store to place an order for a shirt, and the shopkeeper went to the factory to get the corresponding shirt. At this time, Xiao Ming and Xiao Xue were in shirtless state, and the shopkeeper also recorded their information (contact information and address), packed the shirts and affixed the express receipt with contact information and address, and handed it to the logistics company together. The logistics company sends the shirts to Xiao Ming and Xiao Xue respectively according to the address and contact information. At this time, Xiao Ming and Xiao Xue have shirts

In this scenario

Store owner and Xiaoming, xiaoxue belongs to a one-to-many dependence, when the store shirt to Xiaoming, xiaoxue, they are from the state of no shirt to have a shirt

The application of the Observer pattern in Spring has four roles:

  1. ApplicationEvent. ApplicationEvent is an event
  2. ApplicationListener, that is, observer.
  3. ApplicationContext. ApplicationContext is the core container in Spring and can act as the event publisher, or event source, in event listeners.
  4. ApplicationEventMulticaster (event management), ApplicationEventMulticaster used for event listener registration and broadcasting of events.

In practical applications, both SMS and email functions need to be used, such as SMS:

/** * SMS listening (asynchronous execution) */
@Component
public class SmsListener implements ApplicationListener<OrderEvent> {


    private static final Logger logger = Logger.getLogger(SmsListener.class);

    @Override
    @Async  
    public void onApplicationEvent(OrderEvent event) {
        System.out.println(Thread.currentThread() + "... Text message listening..." + event.getMessage()+ "..."+ event.getSource()); }}Copy the code

Conclusion: It is easy to understand the function of the observer mode. For example, the observer mode is used in chat tools and group broadcast in daily life to realize the subscription of messages and the change of message status.