class MessageBroker {
constructor() {
this.subscriptions = new Map();
}
subscribe(topic, subscriber) {
let subscribers = this.subscriptions.get(topic);
if (!subscribers) {
subscribers = new Set();
this.subscriptions.set(topic, subscribers);
}
subscribers.add(subscriber);
}
unsubscribe(topic, subscriber) {
const subscribers = this.subscriptions.get(topic);
if (subscribers) {
subscribers.delete(subscriber);
if (subscribers.size === 0) {
this.subscriptions.delete(topic);
}
}
}
publish(topic, message) {
const subscribers = this.subscriptions.get(topic);
if (subscribers) {
subscribers.forEach(subscriber => {
subscriber.receive(topic, message);
});
}
}
}
class Subscriber {
receive(topic, message) {
throw new Error('receive 로직 구현이 필요합니다.')
}
}
class User extends Subscriber {
constructor(name) {
this.name = name;
}
receive(topic, message) {
console.log(`${this.name} 님이 메시지를 받았습니다. ${topic}: ${message}`);
}
}
const messageBroker = new MessageBroker();
const gameSubscriber = new User('bob');
const techSubscriber = new User('alex');
messageBroker.subscribe('game', gameSubscriber);
messageBroker.subscribe('tech', techSubscriber);
messageBroker.publish('game', '피파온라인5 출시');
messageBroker.publish('tech', 'gpt5 출시');