Publish & Subscribe Design Pattern

  • This pattern is used to provide communications between objects in a program. There are two types of classes which these objects belong to:
    •     1. Publisher
    •     2. Subscriber

    • Publishers publish a message to a communication medium like a queue and the subscribers subscribe to this communication medium to receive the messages they are interested in. However, neither publishers nor subscribers know each others. Publishers only know where to send the message and the subscribers only know where to get the message from.

      A good example regarding the usage of this design pattern is the MQTT protocol. 

    • In MQTT; before publishing a message, publisher needs to know the "topic" of the message which is a property in MQTT protocol to be able to group messages. After publishers publishes a message to a certain topic on the communication medium called MQTT broker, the subscribers can listen to any topic they are interested in by subscribing to the topics they are interested in. To be able to subscribe to multiple topics at once, simple regular expressions are available.

    • In this way, publishers can publish a single message to to a certain topic, hence reaching to multiple subscribers listening to this topic; and subscribers can listen to multiple topics to which messages are published by one or more publishers. 
    Unidirectional Publish & Subscribe Case
  • In the image above, we can see a unidirectional publish & subscribe scenario where a publisher publishes message “A” to a MQTT broker such as mosquitto and “A” has two subscribers and another publisher publishes message “B” whereas “B” has only one subscriber. In this design pattern, publisher can be subscribers and subscribers can be publishers interchangeably if desired.