在上篇博客 用java观察者模式解耦经典三层架构 的最后,用了一个Client类把Listener的实现类注册到了LoginEventSource类中,如果需要添加新的逻辑,添加新的listener类后,还是需要修改Client类,那么我们可以借助spring提供的容器来帮助我们完善观察者模式。
在spring,在src下建立spring配置文件
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- EventSource -->
<bean id="loginEventSource" class="com.tgb.chargeSystem.LoginEventSource">
</bean>
<!-- Listener -->
<bean id="loginLogListener" class="com.tgb.chargeSystem.LoginLogListener">
</bean>
<bean id="loginVerificationListener" class="com.tgb.chargeSystem.LoginVerificationListener">
</bean>
<bean id="registerLoginVerificationListener" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<ref local="loginEventSource" />
</property>
<property name="targetMethod">
<value>registerListener</value>
</property>
<property name="arguments">
<list>
<ref bean="loginVerificationListener" />
</list>
</property>
</bean>
<bean id="registerLoginLogListener" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<ref local="loginEventSource" />
</property>
<property name="targetMethod">
<value>registerListener</value>
</property>
<property name="arguments">
<list>
<ref bean="loginLogListener" />
</list>
</property>
</bean>
通过MethodInvokingFactoryBean,我们可以通过配置文件把Listener注册到对应的事件源,因此避免了在类中的硬编码。
而client代码则改为
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
LoginEventSource loginEventSource=(LoginEventSource)ctx.getBean("loginEventSource");
loginEventSource.notifyListenner();