1-Spring之观察者模式
Java、Google Guava都提供了观察者模式的实现框架。Java提供的框架比较简单,只包含java.util.Observable和java.util.Observer两个类。Google Guava提供的框架功能比较完善和强大:通过EventBus事件总线来实现观察者模式。实际上,Spring也提供了观察者模式的实现框架。
Spring中实现的观察者模式包含三部分:Event事件(相当于消息)、Listener监听者(相当于观察者)、Publisher发送者(相当于被观察者)。我们通过一个例子来看下,Spring提供的观察者模式是怎么使用的。
// Event事件
public class DemoEvent extends ApplicationEvent {
private String message;
public DemoEvent(Object source, String message) {
super(source);
}
public String getMessage() {
return this.message;
}
}
// Listener监听者
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
@Override
public void onApplicationEvent(DemoEvent demoEvent) {
String message = demoEvent.getMessage();
System.out.println(message);
}
}
// Publisher发送者
@Component
public class DemoPublisher {
@Autowired
private ApplicationContext applicationContext;
public void publishEvent(DemoEvent demoEvent) {
this.applicationContext.publishEvent(demoEvent);
}
}
框架使用起来并不复杂,主要包含三部分工作:定义一个继承ApplicationEvent的事件(DemoEvent);定义一个实现了ApplicationListener的监听器(DemoListener);定义一个发送者(DemoPublisher),发送者调用ApplicationContext来发送事件消息。
ApplicationContext只是一个接口,具体的代码实现包含在它的实现类AbstractApplicationContext中。真正的消息发送,实际上是通过Appl

本文介绍了Spring框架中观察者模式、模板模式、适配器模式、策略模式、组合模式、装饰器模式和工厂模式的运用,展示了Spring如何简化开发并提供扩展性。
最低0.47元/天 解锁文章
1172

被折叠的 条评论
为什么被折叠?



