Day 69: Mastering Publish-Subscribe Pattern | Harshil Chovatiya
Publish-Subscribe Pattern Basics:
The Publish-Subscribe Pattern is another powerful design pattern, fostering communication between components without them being directly aware of each other. In this pattern, there's a central message broker, often referred to as a topic or channel, that facilitates communication between publishers and subscribers.
Example: Overview of Publish-Subscribe Pattern:
// Message Broker
class MessageBroker {
constructor() {
this.subscribers = {};
}
subscribe(topic, subscriber) {
if (!this.subscribers[topic]) {
this.subscribers[topic] = [];
}
this.subscribers[topic].push(subscriber);
}
unsubscribe(topic, subscriber) {
if (this.subscribers[topic]) {
this.subscribers[topic] = this.subscribers[topic].filter(sub => sub !== subscriber);
}
}
publish(topic, message) {
if (this.subscribers[topic]) {
this.subscribers[topic].forEach(subscriber => subscriber.receive(message));
}
}
}
// Subscriber
class Subscriber {
constructor(name) {
this.name = name;
}
receive(message) {
console.log(`${this.name} received message: ${message}`);
}
}
// Usage
const broker = new MessageBroker();
const subscriber1 = new Subscriber("Subscriber 1");
const subscriber2 = new Subscriber("Subscriber 2");
broker.subscribe("news", subscriber1);
broker.subscribe("sports", subscriber2);
broker.publish("news", "Breaking News: Important Event");
broker.publish("sports", "Goal! Team scores!");
broker.unsubscribe("news", subscriber1);
broker.publish("news", "No updates for unsubscribed subscriber");
Implementing Publish-Subscribe:
Let's delve into the implementation details of the Publish-Subscribe Pattern.
Example: Coding the Publish-Subscribe Pattern:
class PubSub {
constructor() {
this.topics = {};
}
subscribe(topic, callback) {
if (!this.topics[topic]) {
this.topics[topic] = [];
}
this.topics[topic].push(callback);
}
unsubscribe(topic, callback) {
if (this.topics[topic]) {
this.topics[topic] = this.topics[topic].filter(cb => cb !== callback);
}
}
publish(topic, data) {
if (this.topics[topic]) {
this.topics[topic].forEach(callback => callback(data));
}
}
}
// Usage
const pubsub = new PubSub();
const subscriberA = data => console.log(`Subscriber A received: ${data}`);
const subscriberB = data => console.log(`Subscriber B received: ${data}`);
pubsub.subscribe("news", subscriberA);
pubsub.subscribe("news", subscriberB);
pubsub.publish("news", "Breaking News: Important Event");
pubsub.unsubscribe("news", subscriberA);
pubsub.publish("news", "No updates for unsubscribed subscriber");
Conclusion:
Mastering the Publish-Subscribe Pattern is essential for building scalable and modular applications. This pattern enables effective communication between different components, promoting a decoupled architecture. As you incorporate this pattern into your projects, you'll experience improved code organization and maintainability. Stay tuned for more advanced patterns in the upcoming days.
Comments
Post a Comment