The publish-subscribe (pub/sub) pattern is a messaging paradigm where senders (publishers) don't send messages directly to specific receivers. Instead, they publish messages to topics or channels, and receivers (subscribers) express interest in specific topics. This creates a loose coupling between components - publishers don't need to know who will receive their messages, and subscribers don't need to know who sent them.
In pub/sub systems, there are three key components: publishers that send messages, subscribers that receive messages, and a message broker that manages the routing between them. The broker maintains a registry of which subscribers are interested in which topics, and when a message is published to a topic, the broker delivers it to all registered subscribers.
This pattern is incredibly useful in software architecture because it promotes loose coupling and scalability. Components can communicate without direct references to each other, making systems more modular and easier to maintain. It's particularly powerful in event-driven architectures where many parts of a system need to react to the same events.
The pub/sub pattern is different from simple observer patterns because it typically involves named topics or channels rather than direct object references. This makes it more flexible for complex systems where you want to organize messages by category or type.
1# Simple example of pub/sub concepts
2class SimpleEventSystem:
3 def __init__(self):
4 self.listeners = {}
5
6 def on(self, event_name, callback):
7 if event_name not in self.listeners:
8 self.listeners[event_name] = []
9 self.listeners[event_name].append(callback)
10
11 def emit(self, event_name, data):
12 if event_name in self.listeners:
13 for callback in self.listeners[event_name]:
14 callback(data)
15
16# Usage
17events = SimpleEventSystem()
18events.on('file_uploaded', lambda file: print(f'Processing {file}'))
19events.on('file_uploaded', lambda file: print(f'Logging {file}'))
20events.emit('file_uploaded', 'document.pdf')