type MessageHandler = (message: any) => void; class MessageBus { private subscribers: Map = new Map(); // Subscribe to a specific message type subscribe(messageType: string, handler: MessageHandler): void { if (!this.subscribers.has(messageType)) { this.subscribers.set(messageType, []); } this.subscribers.get(messageType)!.push(handler); } // Unsubscribe a specific handler from a message type unsubscribe(messageType: string, handler: MessageHandler): void { const handlers = this.subscribers.get(messageType); if (handlers) { this.subscribers.set( messageType, handlers.filter((h) => h !== handler) ); } } // Publish a message of a specific type publish(messageType: string, message: any): void { const handlers = this.subscribers.get(messageType); if (handlers) { handlers.forEach((handler) => handler(message)); } } } // Usage example const messageBus = new MessageBus(); // Subscriber 1 messageBus.subscribe("orderPlaced", (message) => { console.log("Inventory Service: Order received:", message); }); // Subscriber 2 messageBus.subscribe("orderPlaced", (message) => { console.log("Notification Service: Sending confirmation for:", message); }); // Publish an event messageBus.publish("orderPlaced", { orderId: 123, product: "Laptop", quantity: 1 }); // Another example: Unsubscribe a handler const shippingHandler = (message: any) => { console.log("Shipping Service: Preparing package for:", message); }; messageBus.subscribe("orderPlaced", shippingHandler); messageBus.publish("orderPlaced", { orderId: 124, product: "Phone", quantity: 2 }); // Unsubscribe the shipping handler messageBus.unsubscribe("orderPlaced", shippingHandler); // Test after unsubscribing messageBus.publish("orderPlaced", { orderId: 125, product: "Tablet", quantity: 3 });