This is a space that holds a collection of my personal work and ideas
Behavioral Patterns - State Pattern Exercise
Posted on 06/26/2018
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.
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
Components:
Vending Machine (The state machine that has multiple states) - VendingMachine
State (The interface that defines all operations that each state should have) - State
Concrete States (All possible states of the vending machine) - CardSwipedAcceptedState, CardSwipedRejectedState, ItemSelectedState, SoldState, SoldOutState.
Client (The user who uses the vending machine) - App
Tips
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.