...

/

Class Diagram for the Vending Machine

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:

  1. NoMoneyInsertedState

    1. insertMoney: Records the inserted amount and transitions the machine to the MoneyInsertedState.

    2. selectProduct: Rejects the request with a message (e.g., “Please insert money first”).

  2. MoneyInsertedState

    1. insertMoney: Adds to the current balance.

    2. selectProduct:

      1. Checks if the selected product is available and compares the current balance to the product price:

        1. Underpaid: Returns all inserted money and resets to NoMoneyInsertedState.

        2. Exact payment: Dispenses the selected product and transitions to DispenseState.

        3. Overpayment: Dispenses the product, returns the change, and transitions to DispenseState.

  3. DispenseState

    1. insertMoney: Does not accept any new actions; prompts the user to wait (e.g., “Please wait, dispensing in progress…”).

    2. selectProduct: Same as above; defers all actions while dispensing.

    3. After the ...