用 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 管理一個執行緒池