In messaging systems or message brokers, the Observer pattern is used to implement the publish-subscribe model. Publishers (subjects) publish messages to a topic, and subscribers (observers) receive messages related to topics they are interested in.
// Subject (Publisher)
public class MessageBroker
{
private Dictionary>> topics = new Dictionary>>();
// Method to subscribe to a topic
public void Subscribe(string topic, Action callback)
{
if (!topics.ContainsKey(topic))
{
topics[topic] = new List>();
}
topics[topic].Add(callback);
}
// Method to publish a message to a topic
public void Publish(string topic, string message)
{
if (topics.ContainsKey(topic))
{
foreach (var callback in topics[topic])
{
callback(message);
}
}
}
}
// Observer (Subscriber)
public class MessageSubscriber
{
public MessageSubscriber(MessageBroker broker, string topic)
{
broker.Subscribe(topic, HandleMessage);
}
private void HandleMessage(string message)
{
Console.WriteLine($"Received message: {message}");
// Process the received message here
}
}
// Example usage
public class Program
{
public static void Main()
{
MessageBroker broker = new MessageBroker();
MessageSubscriber subscriber1 = new MessageSubscriber(broker, "topic1");
MessageSubscriber subscriber2 = new MessageSubscriber(broker, "topic2");
// Publish messages
broker.Publish("topic1", "Hello, topic 1 subscribers!");
broker.Publish("topic2", "Greetings, topic 2 subscribers!");
}
}
Overall, the Observer pattern provides a flexible way to establish relationships between objects where one object (the subject) changes state and notifies its dependents (observers) automatically, promoting decoupling and flexibility in system design.