Loading...
Learn Design Vending Machine — a key concept for LLD interviews.
A vending machine has clear states: Idle (waiting for selection), HasMoney (coins inserted), Dispensing (releasing product), and OutOfStock. Each state responds differently to the same actions (insert coin, select product, dispense).
interface VendingState {
insertCoin(amount: number): void
selectProduct(code: string): void
dispense(): void
cancelTransaction(): void
}
class IdleState implements VendingState {
constructor(private machine: VendingMachine) {}
insertCoin(amount: number): void {
this.machine.addBalance(amount)
this.machine.setState(new HasMoneyState(this.machine))
}
selectProduct(code: string): void {
this.machine.displayMessage("Insert money first")
}
dispense(): void {
this.machine.displayMessage("Insert money and select product")
}
cancelTransaction(): void {
this.machine.displayMessage("No transaction to cancel")
}
}How should you implement the vending machine states?