Blog

Filter posts by Category Or Tag of the Blog section!

publish subscribe pattern

Saturday, 24 April 2021

The publish-Subscribe pattern is a messaging pattern in which publishers and subscribers are decoupled from each other. Publishers send messages (events) to a central topic or message broker without any knowledge of the subscribers. Subscribers can then register their interest in receiving messages related to specific topics with the message broker.

When a message is published on a topic, the message broker distributes the message to all the subscribers who have registered an interest in that topic. This allows for a flexible and scalable system, where publishers and subscribers can be added or removed dynamically without affecting the overall system.

The key components of the Publish-Subscribe pattern are:

  • Publisher: A component that publishes messages on a topic.
  • Subscriber: A component that subscribes to a topic and receives messages related to that topic.
  • Topic: A named channel or category to which messages are published and subscribers register their interest.
  • Message Broker: A central component that receives messages from publishers and distributes them to subscribers who have registered their interest in specific topics.

The publish-Subscribe pattern is widely used in distributed systems, event-driven architectures, and real-time applications where timely and efficient message delivery is required. As an example in C#, take a look at this:

 

using System;

using System.Collections.Generic;



// Publisher

class NewsPublisher

{

    // Dictionary to hold subscribers and their subscriptions

    private Dictionary<string, List<ISubscriber>> _subscribers = new Dictionary<string, List<ISubscriber>>();



    // Method to subscribe a subscriber to a topic

    public void Subscribe(string topic, ISubscriber subscriber)

    {

        if (_subscribers.ContainsKey(topic))

        {

            _subscribers[topic].Add(subscriber);

        }

        else

        {

            _subscribers.Add(topic, new List<ISubscriber> { subscriber });

        }

    }



    // Method to unsubscribe a subscriber from a topic

    public void Unsubscribe(string topic, ISubscriber subscriber)

    {

        if (_subscribers.ContainsKey(topic))

        {

            _subscribers[topic].Remove(subscriber);

        }

    }



    // Method to publish news to subscribers of a topic

    public void Publish(string topic, string news)

    {

        if (_subscribers.ContainsKey(topic))

        {

            foreach (var subscriber in _subscribers[topic])

            {

                subscriber.ReceiveNews(news);

            }

        }

    }

}



// Subscriber interface

interface ISubscriber

{

    void ReceiveNews(string news);

}



// Subscriber implementation

class NewsSubscriber : ISubscriber

{

    private string _name;



    public NewsSubscriber(string name)

    {

        _name = name;

    }



    public void ReceiveNews(string news)

    {

        Console.WriteLine($"{_name} received news: {news}");

    }

}



// Example usage

static void Main(string[] args)

{

    // Create publisher

    var newsPublisher = new NewsPublisher();



    // Create subscribers

    var subscriber1 = new NewsSubscriber("Subscriber 1");

    var subscriber2 = new NewsSubscriber("Subscriber 2");



    // Subscribe subscribers to topics

    newsPublisher.Subscribe("Sports", subscriber1);

    newsPublisher.Subscribe("Politics", subscriber1);

    newsPublisher.Subscribe("Politics", subscriber2);



    // Publish news to subscribers of a topic

    newsPublisher.Publish("Sports", "New soccer league announced");

    newsPublisher.Publish("Politics", "Election results announced");



    // Unsubscribe a subscriber from a topic

    newsPublisher.Unsubscribe("Politics", subscriber1);



    // Publish news to subscribers of a topic

    newsPublisher.Publish("Politics", "New law passed");

}

 

In this example, we have a NewsPublisher class that holds a dictionary of subscribers and their subscriptions to different topics. Subscribers can subscribe and unsubscribe from topics using the Subscribe and Unsubscribe methods of the publisher. When news is published on a topic using the Publish method, the publisher notifies all subscribers subscribed to that topic by calling their ReceiveNews method.

We also have a NewsSubscriber class that implements the ISubscriber interface. Subscribers can receive news by implementing the ReceiveNews method of the interface. In this example, we simply print the news received by a subscriber to the console.

comments powered by Disqus