Class Diagram for the Vending Machine
Learn to create a class diagram for the vending machine using the bottom-up approach.
In this lesson, we use a bottom-up approach to identify and design the classes and interfaces for our Vending Machine system. The focus is clear responsibility separation, applying the State design pattern, and modeling relationships that reflect real-world constraints. Let’s explore each component and how they work together to realize our requirements.
Components of a vending machine
As mentioned, we should design the vending machine using a bottom-up approach.
State Pattern and State
To manage the Vending Machine’s changing behavior depending on its current mode, we use the State design pattern. This pattern encapsulates the machine’s different operational “states” as separate classes, each handling user actions in its way.
State interface
We define a State
interface (or abstract base class), which exposes the two main user-facing actions:
insertMoney(amount)
: For inserting cash into the machine.selectProduct(rackNumber)
: For selecting a product to purchase.
The machine is in exactly one of the following three concrete states at any moment. Each state provides its logic for these actions:
NoMoneyInsertedState
insertMoney
: Records the inserted amount and transitions the machine to theMoneyInsertedState
.selectProduct
: Rejects the request with a message (e.g., “Please insert money first”).
MoneyInsertedState
insertMoney
: Adds to the current balance.selectProduct
:Checks if the selected product is available and compares the current balance to the product price:
Underpaid: Returns all inserted money and resets to
NoMoneyInsertedState
.Exact payment: Dispenses the selected product and transitions to
DispenseState
.Overpayment: Dispenses the product, returns the change, and transitions to
DispenseState
.
DispenseState
insertMoney
: Does not accept any new actions; prompts the user to wait (e.g., “Please wait, dispensing in progress…”).selectProduct
: Same as above; defers all actions while dispensing.After the ...