Design patterns 用Java发布-订阅
示例
鉴于YouTube,Facebook和其他社交媒体服务的兴起,发布者-订阅者是一个熟悉的概念。基本概念是,Publisher有谁创造内容,Subscriber谁消费内容。每当Publisher生成内容时,都会Subscriber通知每个内容。Subscribers理论上可以订阅多个发行商。
通常ContentServer在发布者和订阅者之间有一个,以帮助调解消息传递
public class Publisher {...
public Publisher(Topic t) {
this.topic= t;
}
public void publish(Message m) {
ContentServer.getInstance().sendMessage(this.topic, m);
}
}
public class ContentServer {private Hashtable<Topic, List<Subscriber>> subscriberLists;
private static ContentServer serverInstance;
public static ContentServer getInstance() {
if (serverInstance == null) {
serverInstance = new ContentServer();
}
return serverInstance;
}
private ContentServer() {
this.subscriberLists= new Hashtable<>();
}
public sendMessage(Topic t, Message m) {
List<Subscriber> subs = subscriberLists.get(t);
for (Subscriber s : subs) {
s.receivedMessage(t, m);
}
}
public void registerSubscriber(Subscriber s, Topic t) {
subscriberLists.get(t).add(s);
}
public class Subscriber {public Subscriber(Topic...topics) {
for (Topic t : topics) {
ContentServer.getInstance().registerSubscriber(this, t);
}
}
public void receivedMessage(Topic t, Message m) {
switch(t) {
...
}
}
}
通常,pub-sub设计模式是在考虑多线程视图的情况下实现的。一种较常见的实现将每个都Subscriber视为一个单独的线程,并ContentServer管理线程池
以上是 Design patterns 用Java发布-订阅 的全部内容, 来源链接: utcz.com/z/340655.html