用spring实现察看者筹划情势[Java编程]
本文“用spring实现察看者筹划情势[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
察看者计划情势其实就是一种公布预订的计划情势,大家都知道JMS里面有公布预订的情势,也就是有一个一对多的关系,一个公布者,然后有N多个消费者,一旦公布者发出消息,那么全部预订的消费者都将收到消息.
普通的实现办法大家大概都很熟习了;
1.传统察看者计划情势编写办法:
举例阐明:
公布者类: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("大家好啊");//广播消息
}
}
传统的察看者计划办法公布者和预定者的接洽是硬编码在程序里面的.
以上是“用spring实现察看者筹划情势[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |