Behavioral Patterns - State Pattern Exercise


The State Pattern allows an object to alter its behavior when its internal state changes. It tremendously reduces the complexity when introducing more states later to the object. In this exercise, we will use the State Pattern to create a modern vending machine to understand the components of the State Pattern.

Reading Materials

  1. (10 minutes reading)

Practice Materials

  1. Use the State Pattern to create a modern vending machine that does the following things:
  • It sells different kinds of fruit
  • It has the following states:
    • card swiped accepted
    • card swiped rejected
    • item selected
    • sold
    • sold out
  • each state has the following operations
    • swipe card
    • select item
    • confirm
    • cancel
    • dispense


  1. Vending Machine (The state machine that has multiple states) - VendingMachine
  2. State (The interface that defines all operations that each state should have) - State
  3. Concrete States (All possible states of the vending machine) - CardSwipedAcceptedState, CardSwipedRejectedState, ItemSelectedState, SoldState, SoldOutState.
  4. Client (The user who uses the vending machine) - App


  • A key-value pair like data structure could be used to keep track of the inventory of the vending machine.
  • The state machine needs to keep its internal state.
  • some mock helper methods could be used to print out generic invalid operation errors and validate cards.


Vending Machine Example

Questions to discuss

  1. What are the common use cases to apply a State Pattern?
  2. What needs to be done if multiple instances of the vending machine are instantiated?
    • move concrete state instances to shared static instances.
    • instead of passing in an instance of vending machine from the state constructor, passing the reference when each state operation is called.


  1. The information which you have provided is very good and essential for everyone. Keep sharing this kind of information. Thank you. Vending Machine China Manufacturer


Post a Comment

Popular posts from this blog

Creating a Library Project for Spring Boot

Spring Data Repository Query Precedence Tricks

Overwriting Spring Security Context through Filter