Design a simple Vending Machine
Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2019-12-14
Problem Statement
Design a vending machine that allows users to select products, insert money, and receive items along with change. The system should manage inventory, handle payments, and track transactions.
Functional Requirements (FR)
Product Management
•Add, update, or remove products.
•Track product details: name, price, quantity, and code/ID.
User Interaction
•Display available products.
•Accept user selection.
•Accept payment (coins, bills, or digital payment).
•Dispense product if sufficient payment is received.
•Return change if overpaid.
•Handle insufficient funds gracefully.
Transaction Management
•Record each transaction: product purchased, payment received, change returned, timestamp.
Inventory & Refill
•Track remaining stock.
•Notify when a product is out of stock or low.
•Refill inventory as needed.
Suggested Classes & Responsibilities
Class: VendingMachine
•Attributes:
•inventory → map of productCode → Product
•balance → total cash in machine
•transactions → list of Transaction objects
•Methods:
•selectProduct(productCode)
•insertMoney(amount)
•dispenseProduct()
•returnChange()
•addProduct(product)
•removeProduct(productCode)
Class: Product
•Attributes: productCode, name, price, quantity
•Methods: updateQuantity(qty)
Class: Transaction
•Attributes: transactionId, productCode, amountPaid, changeReturned, timestamp
Class: Payment (Optional if digital payments supported)
•Attributes: paymentType (cash, card, digital), amount
•Methods: processPayment(amount)
Data Flow (High-Level)
1.User selects a product → VendingMachine.selectProduct().
2.User inserts money → VendingMachine.insertMoney().
3.System checks if sufficient money is inserted:
•If yes → dispense product and return change.
•If no → prompt for additional money or cancel.
4.Update inventory and record transaction.
5.System notifies if product is out of stock.
Key Design Considerations
•Atomic Transactions: Ensure product dispensing and change return are consistent.
•Inventory Management: Prevent selling out-of-stock items.
•Extensibility: Support multiple payment types, promotional discounts, or product bundles.
•Thread-Safety: If multiple users can interact simultaneously (e.g., in a networked vending machine).
•Error Handling: Handle invalid selections, insufficient funds, or payment failures.