用Spring提升java觀察者模式靈活性

在上篇博客 用java觀察者模式解耦經典三層架構 的最後,用了一個Client類把Listener的實現類註冊到了LoginEventSource類中,假設需要加入�新的邏輯,加入�新的listener類後,仍是需要改動Client類,那麼咱們可以藉助spring提供的容器來幫助咱們無缺觀察者模式。html


在spring,在src下創建spring配置文件java

	<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代碼則改成spring

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		LoginEventSource loginEventSource=(LoginEventSource)ctx.getBean("loginEventSource");
		loginEventSource.notifyListenner();
相關文章
相關標籤/搜索