欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > spring boot 观察者设计模式代码实现教程

spring boot 观察者设计模式代码实现教程

2025/6/8 11:51:33 来源:https://blog.csdn.net/weixin_40986713/article/details/144081713  浏览:    关键词:spring boot 观察者设计模式代码实现教程

spring boot 观察者设计模式实现

在Spring Boot中实现观察者设计模式可以通过使用事件发布/订阅机制来完成。Spring框架本身提供了一套完善的事件监听和处理机制,这使得我们能够很方便地利用观察者模式。

下面是一个简单的例子,展示了如何在Spring Boot应用中实现观察者模式。

1. 创建自定义事件

首先,我们需要创建一个自定义事件类,这个类需要继承ApplicationEvent类。

import org.springframework.context.ApplicationEvent;public class CustomEvent extends ApplicationEvent {private String message;public CustomEvent(Object source, String message) {super(source);this.message = message;}public String getMessage() {return message;}
}

2. 创建事件监听器

接下来,我们需要创建一个或多个监听器类,这些类会监听并响应特定的事件。监听器类需要实现ApplicationListener接口,并重写onApplicationEvent方法。

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;@Component
public class CustomEventListener {@EventListenerpublic void handleCustomEvent(CustomEvent event) {System.out.println("Received custom event - Message: " + event.getMessage());}
}

在这个例子中,我们使用了@EventListener注解来简化事件监听器的编写。这种方式比直接实现ApplicationListener接口更加简洁。

3. 发布事件

最后,我们需要在某个地方发布事件。这通常是在服务层的方法中完成的,通过调用ApplicationEventPublisherpublishEvent方法来实现。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;@Service
public class EventPublisherService {private final ApplicationEventPublisher publisher;@Autowiredpublic EventPublisherService(ApplicationEventPublisher publisher) {this.publisher = publisher;}public void publish(String message) {CustomEvent event = new CustomEvent(this, message);publisher.publishEvent(event);}
}

4. 测试事件发布与监听

为了验证事件发布和监听是否工作正常,可以在控制器或者其他组件中调用EventPublisherServicepublish方法。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class EventController {private final EventPublisherService eventPublisherService;@Autowiredpublic EventController(EventPublisherService eventPublisherService) {this.eventPublisherService = eventPublisherService;}@GetMapping("/publish")public String publishEvent(@RequestParam String message) {eventPublisherService.publish(message);return "Event published!";}
}

现在,当你访问/publish?message=Hello这个URL时,就会触发一个CustomEvent事件,监听器会接收到这个事件并打印出消息。

以上就是在Spring Boot中实现观察者设计模式的基本步骤。通过这种方式,可以很容易地将松耦合的消息传递机制引入到应用程序中。

对比java 观察者设计模式实现

在Java中,观察者设计模式是一种行为设计模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。当这个主题对象的状态发生变化时,所有依赖于它的观察者对象都会得到通知并被自动更新。

Java提供了内置的支持来实现观察者模式,主要通过java.util.Observable类和java.util.Observer接口。下面是一个简单的例子来说明如何使用这两个类来实现观察者模式。

1. 创建Observable(可观察对象)

首先,创建一个继承自java.util.Observable的类。在这个类中,我们需要调用setChanged()方法来标记状态已经改变,然后调用notifyObservers()方法来通知所有的观察者。

import java.util.Observable;public class WeatherData extends Observable {private float temperature;private float humidity;private float pressure;public void measurementsChanged() {// 当数据改变时,设置标志位,表示发生了变化setChanged();// 通知所有注册的观察者notifyObservers();}public void setMeasurements(float temperature, float humidity, float pressure) {this.temperature = temperature;this.humidity = humidity;this.pressure = pressure;measurementsChanged();}public float getTemperature() {return temperature;}public float getHumidity() {return humidity;}public float getPressure() {return pressure;}
}

2. 创建Observer(观察者)

接下来,创建一个或多个实现了java.util.Observer接口的类。这些类需要实现update()方法,该方法会在被观察对象调用notifyObservers()方法时被触发。

import java.util.Observable;
import java.util.Observer;public class CurrentConditionsDisplay implements Observer {@Overridepublic void update(Observable o, Object arg) {if (o instanceof WeatherData) {WeatherData weatherData = (WeatherData) o;System.out.println("Current conditions: " + weatherData.getTemperature()+ "F degrees and " + weatherData.getHumidity() + "% humidity");}}
}

3. 使用Observable和Observer

最后,创建WeatherData实例,并将其添加到CurrentConditionsDisplay观察者的观察列表中。当天气数据改变时,观察者会自动收到更新。

public class WeatherStation {public static void main(String[] args) {WeatherData weatherData = new WeatherData();// 创建观察者CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay();// 注册观察者weatherData.addObserver(currentDisplay);// 模拟数据变化weatherData.setMeasurements(80, 65, 30.4f);weatherData.setMeasurements(82, 70, 29.2f);weatherData.setMeasurements(78, 90, 29.2f);}
}

以上就是一个简单的Java中使用观察者设计模式的例子。注意,在现代Java开发中,由于Observable类和Observer接口的功能相对有限,很多开发者倾向于使用更灵活的框架或者库(如JavaFX中的属性绑定、ReactiveX等)来实现类似的功能。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词