Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement the Observer pattern and the event programming Model in Spring

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

The knowledge of this article "how to achieve the Observer pattern and the event programming model in Spring" is not understood by most people, so the editor summarizes the following contents, detailed contents, clear steps, and certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve the Observer pattern and the event programming model in Spring" article.

What is the Observer Mode?

In real life, the observer model can be seen everywhere, such as

Watching the news, as long as the news starts to play, the news will be pushed to the subscribers who subscribe to the news. Here, the news is the observer and the user is the observer.

Wechat official account, if a user subscribes to an official account, then he will receive a message from the official account, then the official account is the observed, and the user is the observer.

The water heater, assuming that the water heater is composed of three parts, the water heater, alarm, monitor, and water heater are only responsible for boiling water. When the water temperature reaches the set temperature, the alarm is notified and the alarm goes out. The display also needs to subscribe to the water heating event of the water heater to obtain the water temperature and display. The water heater is the observed, the alarm, the monitor is the observer.

Here, we can see that the observer has lost the right of autonomy and can only passively receive events from the observed and cannot observe them actively. The observer becomes the recipient, and the observed becomes the attack. [the observed] only notifies the [observer] and does not care what action the [observer] will perform after receiving the notice.

In the design pattern, the observed is called the theme.

In the observer design pattern, there are generally four roles:

Abstract topic roles (Subject)

Specific subject roles (ConcreteSubject)

Abstract Observer role (Observer)

Specific observer role (ConcreteObserver)

Among them, the topic needs to have a list field to hold the reference of the observer, to provide two methods (virtual method), that is, to delete the observer and to add the observer, and to provide a method to be called by the client to inform the observers that the events you care about (subscribe to) have been pushed to you.

Next, I will implement the observer mode in three ways.

Classic

Public class News {

Private String title

Private String content

Public String getTitle () {

Return title

}

Public void setTitle (String title) {

This.title = title

}

Public String getContent () {

Return content

}

Public void setContent (String content) {

This.content = content

}

}

This class is not a required class in the observer mode and is used to store information about events.

Public interface Subject {

List peopleList = new ArrayList ()

Default void add (People people) {

PeopleList.add (people)

}

Default void remove (People people) {

PeopleList.remove (people)

}

Void update ()

}

Abstract topic role, in which there is a field peopleList that holds a reference to the Observer and defines two interfaces, which is written by the default interface implementation of Java8. These two interfaces are called for the client to [delete the observer] [add the observer], and provide a method that needs to be overridden by the [specific subject role] to notify each [observer].

Public class NewsSubject implements Subject {

Public void update () {

For (People people: peopleList) {

News news = new News ()

News.setContent ("Today in the street, someone hid in the grass and attacked passers-by, shouting 'long live Demacia')

News.setTitle ("Demacia appeared")

People.update (news)

}

}

}

Specific topic roles, rewrite the methods of [abstract topic roles], circular lists, and notify each [observer].

Public interface People {

Void update (News news)

}

Abstract the observer role, defining an interface, and [concrete observer role] needs to override this method.

Here is the specific observer role:

Public class PeopleA implements People {

@ Override

Public void update (News news) {

System.out.println ("this news is really good")

}

}

Public class PeopleB implements People {

@ Override

Public void update (News news) {

System.out.println ("this news is speechless")

}

}

Public class PeopleC implements People {

@ Override

Public void update (News news) {

System.out.println ("this news is really funny")

}

}

Client:

Public class Main {

Public static void main (String [] args) {

Subject subject = new NewsSubject ()

Subject.add (new PeopleA ())

Subject.add (new PeopleB ())

Subject.add (new PeopleC ())

Subject.update ()

}

}

Run:

When we learn design patterns, we must know the advantages and disadvantages of design patterns, so what are the advantages and disadvantages of observer design patterns?

Advantages:

[topic] and [observer] establish a loosely coupled relationship through abstraction. [topic] only knows which observers are currently available and sends notifications, but does not know what actions [observers] will perform. This is also easy to understand, for example, when the official Wechat account sends a message, it doesn't know what action you will take, whether to open it with a smile or anger, or delete the message directly, or throw your phone into the washing machine to wash it.

In accordance with the principle of opening and closing, if you need to add an Observer, you only need to write a class to implement the Abstract Observer role without changing the original code.

Disadvantages:

The client must know all the observers and perform the operations of adding observers and deleting observers.

If there are many observers, it may take a long time for all observers to receive notification.

Of course, the above advantages and disadvantages are the most intuitive, can be easily understood, and experienced. Other advantages and disadvantages, you can own Baidu.

Lambda

Before introducing this way of writing, it is necessary to introduce the next functional interface, the concept of functional interface has a long history, generally speaking, only a virtual method of the interface is called functional interface, in Java8, due to the emergence of Lambda expression, functional interface shines brilliantly.

We just need to modify the code on the client side:

Public static void main (String [] args) {

Subject subject = new NewsSubject ()

Subject.add (a-> System.out.println ("read the news"))

Subject.add (a-> System.out.println)

Subject.add (a-> System.out.println ("I saw it yesterday")

Subject.update ()

}

Running result:

Using Lambda expressions and functional interfaces, the definition of specific observer role can be omitted, but personally, this does not belong to the strict observer pattern, and the disadvantages are obvious:

The client needs to know the specific implementation of the observer.

If the specific implementation of the observer is complex, the code may not be so clear.

Therefore, this way of writing has some limitations.

To borrow a sentence from the great god

The emergence of design patterns is to make up for the defects of language.

It is precisely because of the upgrade of the language that some design patterns have changed to some extent. In addition to the observer pattern, there are also template method patterns, responsibility chain patterns and so on, all of which have changed due to the emergence of Lambda expressions.

JDK

In Java, it provides an interface: Observer, a subclass: Observable, where Observer represents [observer] and Observable represents [topic]. You can use these two subclasses and interfaces to implement the observer pattern:

Public class NewsObservable extends Observable {

Public void update () {

SetChanged ()

NotifyObservers ()

}

}

Public class People1 implements Observer {

@ Override

Public void update (Observable o, Object arg) {

System.out.println ("editor is so boring")

}

}

Public class People2 implements Observer {

@ Override

Public void update (Observable o, Object arg) {

System.out.println ("A picture at the beginning, the content is all made up")

}

}

Client:

Public static void main (String [] args) {

NewsObservable newsObservable = new NewsObservable ()

NewsObservable.addObserver (new People1 ())

NewsObservable.addObserver (new People2 ())

NewsObservable.update ()

}

Running result:

I'm not going to go into this implementation in detail here, because starting with Java9, Java no longer recommends this writing, but instead recommends message queuing. Are you happy to find an excuse not to study Observable,Observer?

Event programming Model in Spring

The event programming model in Spring is the implementation of the observer pattern. SpringBoot uses Spring's event programming model to complete some operations, which is not shown here.

An ApplicationListener interface is defined in Spring. It is known from the name that it is a listener that listens to events of Application. What is Application? it is that ApplicationContext,ApplicationContext has several built-in events. What is easier to understand is:

ContextRefreshedEvent

ContextStartedEvent

ContextStoppedEvent

ContextClosedEvent

From the name point of view, we can see when these events were triggered.

Let me demonstrate the specific usage. For example, I want to listen to the ContextRefreshedEvent event and print a sentence if the event occurs.

@ Component

Public class MyListener implements ApplicationListener {

@ Override

Public void onApplicationEvent (ApplicationEvent applicationEvent) {

If (applicationEvent instanceof ContextRefreshedEvent) {

System.out.println ("refreshed")

}

}

}

@ Configuration

@ ComponentScan

Public class AppConfig {

}

Public static void main (String [] args) {

AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext (AppConfig.class)

}

Running result:

Learning Spring at that time, I had to admire the developers of Spring when I saw that Spring provided a variety of interfaces for programmers to extend Spring without any intrusiveness. Here, too, we can see that there is no shadow of "subscription events" on the client side.

This implementation is not very good, and we can see that we have made a judgment inside the method: whether the received event is ContextRefreshedEvent or not.

The great Spring also provides generic ApplicationListener, which we can refine with generic ApplicationListener:

@ Component

Public class MyListener implements ApplicationListener {

@ Override

Public void onApplicationEvent (ContextRefreshedEvent event) {

System.out.println ("refreshed")

}

}

We can also customize events and publish events using the event programming model in Spring:

First, we need to define an event to implement the ApplicationEvent interface, which means that this is an Application event. In fact, the four built-in events mentioned above also implement the ApplicationEvent interface:

Public class MyEvent extends ApplicationEvent {

Public MyEvent (Object source) {

Super (source)

}

}

You also need to define a listener, and of course, here you need to listen for MyEvent events:

@ Component

Public class MyListener implements ApplicationListener {

@ Override

Public void onApplicationEvent (MyEvent event) {

System.out.println ("events I subscribe to have arrived")

}

}

Now that there are events and listeners, is there still a lack of publishers, otherwise who will publish the events?

@ Component

Public class MyEventPublish implements ApplicationEventPublisherAware {

Private ApplicationEventPublisher publisher

@ Override

Public void setApplicationEventPublisher (ApplicationEventPublisher applicationEventPublisher) {

This.publisher = applicationEventPublisher

}

Public void publish (Object obj) {

This.publisher.publishEvent (obj)

}

}

The publisher needs to implement the ApplicationEventPublisherAware interface and override the publish method. As the name implies, this is the publishing method. What is the parameter obj of the method? as a publisher, I should know what event I want to publish and the event source (who triggered it). This obj is used to store such data. Of course, this parameter needs to be passed in manually. SetApplicationEventPublisher is called actively within Spring and can be simply understood as initializing the publisher.

Now there is only one role left. There are listeners, publishers and events. Yes, yes, there is still one trigger missing. After all, there has to be a trigger to trigger the event:

@ Component

Public class Service {

@ Autowired

Private MyEventPublish publish

Public void publish () {

Publish.publish (new MyEvent (this))

}

}

The publish method is called for the client to trigger the event, and you can clearly see that new MyEvent (this) is passed in, so that the publisher can know what event I want to trigger and who triggered the event.

Of course, you also need to leave everything to Spring:

@ Configuration

@ ComponentScan

Public class AppConfig {

}

Client:

Public static void main (String [] args) {

AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext (AppConfig.class)

Context.getBean (Service.class). Publish ()

}

The above is the content of this article on "how to implement the Observer Mode and the event programming Model in Spring". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report