传统观察者设计模式编写方法:
发布者类:Publisher.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Publisher implements Subject {
private List subs= new ArrayList();
private String msg;
// this message is added so I can give
// this class a reason to call notifyListener.
public void setMessage(String message){
System.out.println("我是发布者,我说:" + message);
this.messageText = message;
this.notifyListeners();
}
public void addListener(Subscriber o) {
this.subs.add(o);
}
public void removeListener(Subscriber o) {
if (this.subs.contains(o)){
this.subs.remove(o);
}
}
// call the update method on
// each Subscriber
public void notifyListeners() {
for (Iterator iter = subs.iterator(); iter.hasNext();) {
Subscriber listener = (Subscriber ) iter.next();
listener.update(msg);
}
}
}
预定者类:Subsriber1.java
public class Subsriber1 implements Observer {
public void update(String messageText) {
System.out.println("我的名字是: " + this);
System.out.println("我接收到消息: " + messageText);
}
预定者类:Subsriber2.java
public class Subsriber2 implements Observer {
public void update(String messageText) {
System.out.println("我的名字是: " + this);
System.out.println("我接收到消息: " + messageText);
}
如果按传统的观察者模式编写方法,如果要把发布者和预订者联系在一起的话;还需要有专门的处理类来负责添加这种联系。
例如:
public class ExampleRun {
public static void main(String[] args) {
Publisher pub = new Publisher();
Subsriber1 sub1 = new Subsriber1();
Subsriber2 sub2 = new Subsriber2 ();
pub.addListener(sub1);
pub.addLstener(sub2);
pub.setMessage("大家好啊");//广播消息
}
}
2。采用spring进行优化
首先你肯定要熟悉spring的bean工厂配置原理。
bean工厂的xml配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="sub1" class="Subsriber1"/>
<bean id="sub2" class="Subsriber2"/>
<bean id="pub" class="Publisher"/>
<bean id="bindPubAndSub"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject"><ref local="pub"/></property>
<property name="targetMethod"><value>addListener</value></property>
<property name="arguments">
<list>
<ref bean="sub1"/>
<ref bean="sub2"/>
</list>
</property>
</bean>
</beans>
这里的关键是采用org.springframework.beans.factory.config.MethodInvokingFactoryBean工厂类;来动态
把sub1和sub2注入到pub当中。实现观察者的xml可配置化。
处理类如下:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class ExampleRun {
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"/config/ObserverTest.xml");
Pub pub = (Publisher) ctx.getBean("pub");
pub.setMessage("大家好啊!!!");
}
}