Practice/Amazon/Design a Pub-Sub System for Delivery Drivers
Object Oriented DesignMust
Design and implement a real-time event distribution system for managing driver notifications. The system allows drivers to subscribe to specific event topics (such as weather alerts, route updates, or order assignments) and receive relevant events as they occur. The system must support dynamic topic subscriptions, event validation through custom rules, and efficient message delivery to potentially tens of thousands of concurrent drivers.
Your implementation should handle driver registration, topic-based subscriptions, event publishing with validation, and the ability to extend the system with custom validation logic without modifying the core code.
Example 1: Basic Event Flow
` system = EventDistributionSystem() driver1 = Driver("D001", "Alice") driver2 = Driver("D002", "Bob")
system.register_driver(driver1) system.register_driver(driver2)
system.subscribe("D001", "weather_alert") system.subscribe("D002", "weather_alert")
event = {"type": "storm", "severity": "high", "timestamp": "2024-01-15T10:00:00"} count = system.publish_event("weather_alert", event)
`
Example 2: Multiple Topics
` system.subscribe("D001", "traffic_update") system.subscribe("D001", "order_assignment")
event1 = {"type": "congestion", "location": "Highway 101"} system.publish_event("traffic_update", event1)
event2 = {"type": "new_order", "order_id": "ORD123"} system.publish_event("order_assignment", event2)
`
Example 3: Event Validation
` class PriorityValidator(EventValidator): def validate(self, event): return "priority" in event and event["priority"] in ["low", "medium", "high"]
system.add_validator(PriorityValidator())
valid_event = {"type": "alert", "priority": "high"} system.publish_event("alerts", valid_event) # Published successfully
invalid_event = {"type": "alert", "priority": "urgent"} system.publish_event("alerts", invalid_event) # Rejected by validator `