Hint
Consider the level of coupling and flexibility required in your system to determine whether the Observer or Pub/Sub pattern is more suitable
The Observer and Pub/Sub design patterns are often confused with each other due to their similarities. However, they have distinct differences in their implementation and use cases. The Observer pattern is a one-to-many dependency between objects, where an object (the subject) notifies other objects (the observers) about changes to its state. On the other hand, the Pub/Sub pattern is a many-to-many relationship between objects, where publishers send messages to a topic, and subscribers listen to that topic to receive the messages.
class Subject {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
notifyObservers() {
this.observers.forEach((observer) => observer.update());
}
}
class Observer {
update() {
console.log('Observer update');
}
}
const subject = new Subject();
const observer = new Observer();
subject.addObserver(observer);
subject.notifyObservers();
In contrast, the Pub/Sub pattern can be implemented using a central hub or event bus that handles message passing between publishers and subscribers.
class EventBus {
constructor() {
this.subscribers = {};
}
subscribe(topic, callback) {
if (!this.subscribers[topic]) {
this.subscribers[topic] = [];
}
this.subscribers[topic].push(callback);
}
publish(topic, data) {
if (this.subscribers[topic]) {
this.subscribers[topic].forEach((callback) => callback(data));
}
}
}
const eventBus = new EventBus();
eventBus.subscribe('topic', (data) => console.log(data));
eventBus.publish('topic', 'Hello, world!'); The key difference between the two patterns lies in their coupling and flexibility. The Observer pattern has tight coupling between the subject and observers, whereas the Pub/Sub pattern has loose coupling between publishers and subscribers.