用 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
管理一个线程池