观察者模式
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者模式属于行为型模式。
此处主要基于spring实现观察者模式,废话不多说上干货
首先我们定义一个事件
public class OrderEvent extends ApplicationEvent {
/**
* 观察者中的事件
* 主要作用是传递参,让监听者感知有事件发布
*/
public OrderEvent(Object source) {
super(source);
}
}
之后定义一个事件监听者
@Component
public class MsgListener implements ApplicationListener<OrderEvent> {
/**
* 观察者中的监听者
* 主要是拿到参数做对应的处理
*/
@Override
public void onApplicationEvent(OrderEvent orderEvent) {
String msg= (String) orderEvent.getSource();
System.out.println(msg);
}
}
之后我们就可以愉快的将业务代码中的乱七八糟的东西抽离出来
@Service
public class OrderBiz {
@Autowired
private ApplicationContext applicationContext;
public void test(){
//事件
OrderEvent orderEvent=new OrderEvent("参数");
//发布事件交给spring容器
applicationContext.publishEvent(orderEvent);
}
}
以上主要利用了spring容器进行实现观察者模式,之后我们聊一聊看spring是如何实现的
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);
}
}
}
以上主要是取出容器内所有实现了ApplicationListener接口的对象并且逐一调用invokeListener方法中的doInvokeListener而这个方法又在调用 listener.onApplicationEvent(event);在此处可以看出刚好对应到我们必须复写ApplicationListener中的onApplicationEvent,
其实观察者说白了重要的就是事件怎么发送出去,监听者怎么检测到而已