4. Design Vending Machine
Difficulty: Medium Topics: State Design Pattern, State Machine Key Concepts: Managing state transitions, inventory, handling money.
Phase 1: Requirements Gathering
Goals
Design a Vending Machine that dispenses products based on user selection and payment.
Identify states and transitions.
Handle edge cases like insufficient funds or out-of-stock items.
1. Who are the actors?
User: Selects items, inserts money, collects product and change.
Admin: Restocks items and collects money.
System: Manages inventory, state, and transactions.
2. What are the must-have features? (Core)
Product Selection: User selects an item by code (e.g., A1).
Payment Processing: User inserts coins/notes.
Dispensing: Machine dispenses item if balance >= price.
Change Return: Machine returns excess balance.
State Management: Handle Idle, Selection, Dispensing, OutOfOrder states.
3. What are the constraints?
Concurrency: One user at a time (physical machine).
Hardware Interface: Methods to control motors/display (abstracted here).
Phase 2: Use Cases
UC1: Purchase Item
Actor: User Flow:
User selects an item (State: Idle -> Selection).
System checks inventory.
User inserts money (State: Selection).
If balance >= price, change state to Dispensing.
System dispenses item and returns change.
System resets to Idle state.
UC2: Cancel Request
Actor: User Flow:
User presses cancel during selection.
System refunds inserted money.
System resets to Idle state.
Phase 3: Class Diagram
Step 1: Core Entities
VendingMachine: Context class holding state and inventory.
State (Interface): Defines behavior for states.
Inventory: Manages products and counts.
Product: Item details.
Coin/Note: Money entities (simplified as double for this design).
UML Diagram
Phase 4: Design Patterns
1. State Pattern
Description: Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
Why used: The Vending Machine has distinct behaviors depending on its state (e.g.,
Idle,Selection,Dispensing). The pattern eliminates complexif-elseorswitchstatements by delegating behavior to state objects.
Phase 5: Code Key Methods
Java Implementation
Phase 6: Discussion
Concurrency
Q: How to handle concurrency (two users selecting same last item)?
A: "In
Inventory.deduct(), implement a double-check lock or useAtomicIntegerfor counts. If using database, use optimistic locking."
Extension: Maintenance Mode
Q: How to add new states (e.g., Maintenance)?
A: "Create
MaintenanceStateclass implementingStateinterface. Add transition logic (only Admin can trigger). In Maintenance, all actions likeinsertMoneywould throw exceptions or return error messages."
Hardware Integration
Q: How to handle exact change only?
A: "The machine needs to track its own internal cash inventory. In
DispenseState, check if internal cash can provide the change using a Greedy algorithm (DP or Knapsack for optimal coin combinations)."
Financial Precision (SDE-3 Concept)
Q: Why use double for price/balance? Is this safe?
A: "In this simplified example, yes. However, in production, using
doubleorfloatfor currency leads to floating-point precision errors (e.g.,0.1 + 0.2 = 0.30000000000000004). For financial applications, always useBigDecimalin Java (or store values as integers representing the smallest currency unit, like cents, i.e., $1.50 stored as150)."
SOLID Principles Checklist
S (Single Responsibility):
Inventorymanages stock,Statesmanage transitions,VendingMachineacts as context.O (Open/Closed): New states can be added without modifying existing states significantly.
L (Liskov Substitution): All states implement
Stateinterface correctly.I (Interface Segregation):
Stateinterface covers all necessary actions.D (Dependency Inversion):
VendingMachinedepends onStateinterface, not concrete states.
Last updated