Pub/Sub Model Explained : With TypeScript/ Java Example

The Publish-Subscribe (Pub-Sub) model is a messaging design pattern. It is commonly used in web applications to facilitate communication between different components or modules without requiring them to directly interact with each other. In this model, there are typically three main components:
- Publishers
- Subscribers
- A message broker.
How They Interact
Publishers are responsible for generating and publishing messages, while subscribers register their interest in receiving specific types of messages. The message broker acts as an intermediary, receiving messages from publishers and distributing them to the appropriate subscribers based on predefined criteria.
Real World Use-Case
Consider a real-time chat application where users can join different chat rooms and send messages to other users within those rooms. In this scenario, each chat room can be considered a topic, and users who want to receive messages from a particular room subscribe to that topic. When a user sends a message to a chat room, it is published to the corresponding topic by the publisher component. The message broker then distributes the message to all subscribers who have subscribed to that topic, ensuring that all users in the chat room receive the message in real-time.
Pub/Sub Advantages
The Pub-Sub model offers several advantages for web applications, including;
- Scalability
- Decoupling of components
- Real-time communication.
Decoupling publishers from subscribers, it allows for greater flexibility and scalability, as new components can be added or removed without affecting the overall system.
Additionally, it enables real-time communication between different parts of the application, making it well-suited for use cases such as real-time messaging, notifications, and event-driven architectures. Overall, the Pub-Sub model provides an efficient and scalable way to manage communication between components in web applications, enhancing their responsiveness and usability.
Pub/Sub Model using Javascript/Typescript
Publisher
interface defines the methods for adding, removing, and notifying observers.
interface Publisher {
addObserver(subscriber: Subscriber): void;
removeObserver(subscriber: Subscriber): void;
notifyObservers(message: string): void;
}
ChatRoom
class is a concrete implementation of the Publisher
interface. It maintains a list of subscribers and notifies them when a message is sent.
// Concrete implementation of Publisher
class ChatRoom implements Publisher {
private subscribers: Subscriber[] = [];
addObserver(subscriber: Subscriber): void {
this.subscribers.push(subscriber);
}
removeObserver(subscriber: Subscriber): void {
const index = this.subscribers.indexOf(subscriber);
if (index !== -1) {
this.subscribers.splice(index, 1);
}
}
notifyObservers(message: string): void {
this.subscribers.forEach(subscriber => {
subscriber.receiveMessage(message);
});
}
sendMessage(message: string): void {
this.notifyObservers(message);
}
}
Subscriber
interface defines the method for receiving messages.
// Define the Subscriber interface
interface Subscriber {
receiveMessage(message: string): void;
}
User
class is a concrete implementation of the Subscriber
interface. It receives messages sent by the ChatRoom
.
// Concrete implementation of Subscriber
class User implements Subscriber {
private name: string;
constructor(name: string) {
this.name = name;
}
receiveMessage(message: string): void {
console.log(`${this.name} received message: ${message}`);
}
}
An instance of ChatRoom
is created, and two User
subscribers are added to it. Messages are sent to the chat room, and subscribers receive them accordingly.
// Create a chat room (Publisher)
const chatRoom = new ChatRoom();
// Create users (Subscribers)
const user1 = new User("Alice");
const user2 = new User("Bob");
// Subscribe users to the chat room
chatRoom.addObserver(user1);
chatRoom.addObserver(user2);
// Send a message to the chat room
chatRoom.sendMessage("Hello, everyone!");
// User1 leaves the chat room
chatRoom.removeObserver(user1);
// Send another message to the chat room
chatRoom.sendMessage("Goodbye, everyone!");
Pub/Sub Model Implementation with Java Code
Publisher
interface defines the methods for adding, removing, and notifying observers.
// Define the Publisher interface
interface Publisher {
void addObserver(Subscriber subscriber);
void removeObserver(Subscriber subscriber);
void notifyObservers(String message);
}
ChatRoom
class is a concrete implementation of the Publisher
interface. It maintains a list of subscribers and notifies them when a message is sent.
import java.util.ArrayList;
import java.util.List;
// Concrete implementation of Publisher
class ChatRoom implements Publisher {
private List<Subscriber> subscribers = new ArrayList<>();
@Override
public void addObserver(Subscriber subscriber) {
subscribers.add(subscriber);
}
@Override
public void removeObserver(Subscriber subscriber) {
subscribers.remove(subscriber);
}
@Override
public void notifyObservers(String message) {
for (Subscriber subscriber : subscribers) {
subscriber.receiveMessage(message);
}
}
public void sendMessage(String message) {
notifyObservers(message);
}
}
Subscriber
interface defines the method for receiving messages.
// Define the Subscriber interface
interface Subscriber {
void receiveMessage(String message);
}
User
class is a concrete implementation of the Subscriber
interface. It receives messages sent by the ChatRoom
.
// Concrete implementation of Subscriber
class User implements Subscriber {
private String name;
public User(String name) {
this.name = name;
}
@Override
public void receiveMessage(String message) {
System.out.println(name + " received message: " + message);
}
}
PubSubExample
class demonstrates how the Pub-Sub model works by creating a ChatRoom
and two User
subscribers. Messages are sent to the chat room, and subscribers receive them accordingly.
public class PubSubExample {
public static void main(String[] args) {
// Create a chat room (Publisher)
ChatRoom chatRoom = new ChatRoom();
// Create users (Subscribers)
User user1 = new User("Alice");
User user2 = new User("Bob");
// Subscribe users to the chat room
chatRoom.addObserver(user1);
chatRoom.addObserver(user2);
// Send a message to the chat room
chatRoom.sendMessage("Hello, everyone!");
// User1 leaves the chat room
chatRoom.removeObserver(user1);
// Send another message to the chat room
chatRoom.sendMessage("Goodbye, everyone!");
}
}