spring是目前使用最为广泛的Java框架之一。虽然spring最为核心是IOC和AOP,其中代码实现中很多设计模式得以应用,代码看起来简洁流畅,在日常的软件设计中很值得借鉴。以下是对一些设计模式的理解以及源码解析,希望能给大家对设计模式的理解有所帮助。
更多设计模式更新中.....
(基于spring-4.3.23.RELEASE分析)
如对观察者模式还不是很有概念,可以点击这里。spring中ApplicationEvent事件通知就是观察者模式的变种,巧妙的利用事件驱动机制实现容器刷新。开发者可充分利用该机制,实现框架的深度定制。下面分为几点展开:
ApplicationEventMulticaster是一个接口,定义了事件管理的基本行为,目前spring只有一个实现类和一个抽象类。这里先贴出定义理解各个角色的作用,后边一点点串联整个功能。
public interface ApplicationEventMulticaster { /** * 增加一个具体事件监听器 */ void addApplicationListener(ApplicationListener<?> listener); /** * 增加一个事件监听器 以beanName形式 */ void addApplicationListenerBean(String listenerBeanName); /** * 删除一个具体事件监听器 */ void removeApplicationListener(ApplicationListener<?> listener); /** * 删除一个事件监听器 以beanName形式 */ void removeApplicationListenerBean(String listenerBeanName); /** * 删除所有事件监听器 */ void removeAllListeners(); /** * 发布事件 */ void multicastEvent(ApplicationEvent event); /** * 发布事件 */ void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType); }
ApplicationEvent是事件通知的媒介,也是消息传递的载体。这个类只是继承JDK原生的EventObject,约定为source的事件传递数据 只要理解其作用即可 比较简单所以贴出代码
/** * Class to be extended by all application events. Abstract as it * doesn't make sense for generic events to be published directly. * * @author Rod Johnson * @author Juergen Hoeller */ public abstract class ApplicationEvent extends EventObject { /** use serialVersionUID from Spring 1.2 for interoperability. */ private static final long serialVersionUID = 7099057708183571937L; /** System time when the event happened. */ private final long timestamp; /** * Create a new ApplicationEvent. * @param source the object on which the event initially occurred (never {@code null}) */ public ApplicationEvent(Object source) { super(source); this.timestamp = System.currentTimeMillis(); } /** * Return the system time in milliseconds when the event happened. */ public final long getTimestamp() { return this.timestamp; } }