观察者模式
定义
定义了对象之间的一对多依赖,让多个观察者监听同一个对象的行为,当该行为发生的时候,则做出一定的动作
接下来以以下场景模拟:天气变化了,则发出提示
天气模型
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Weather {
private String address;
private Integer temperature;
private List<Observer> observers;
public void addObserver(Observer observer){
observers.add(observer);
}
public void removeObserver(Observer observer){
observers.remove(observer);
}
public void changeTemperature(int temperature){
this.temperature=temperature;
// 通知所有的观察者
for (Observer observer : observers) {
observer.update(temperature);
}
}
}
观察者的接口
public interface Observer {
void update(Integer temperature);
}
邮件的观察者
public class EmailObserver implements Observer {
@Override
public void update(Integer temperature) {
System.out.println("发邮件告诉用户天气改变了,变为了"+temperature);
}
}
短信观察者
public class MsgObserver implements Observer{
@Override
public void update(Integer temperature) {
System.out.println("发短信告诉用户气温改变了,变为了"+temperature);
}
}
SpringBoot的观察者模式的实践
import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public MyEvent(Object source) {
super(source);
}
}
import org.springframework.context.ApplicationListener;
public class MyEventListener implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
System.out.println("处理自定义事件");
}
}
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
public class MyApplication implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void doSomething(){
System.out.println("doSomething");
applicationEventPublisher.publishEvent(new MyEvent("something"));
}
}
具体执行流程见观察者模式在spring中的应用