State Pattern

This is an introduction to state pattern.

What is State Pattern

Allows an object to alter its behavior when its internal state changes.

Key Points

  1. An object has multiple states.
  2. State is a interface with some methods.
  3. Each specific state implements all method behaviors, includes state shifting.
  4. The object class will hold instance variables for all state types and a State type variable.
  5. Shared methods like setState or variables shared by all state are still in object class.
    • Each state class use object instance to access shared methods/variables.

Gumball Machine Example

Gumball machine has multiple states, all states has same methods(insertCoin, ejectCoin,
dispenseCoin…) but with different behaviors.

State Pattern Solution:

  • Define State interface to hold all diverse behaviors,
  • GumballMachine class
    • holds instance variable for all state class types and one State variable,
    • setState and gumball number variable/getGumballNumber are all in this class,
  • Implement each state class
    • state changes also happens inside these class,
    • GumballMachine instance is passed in to give us access to shared methods/variables.

My Code Example

https://github.com/AudreyMeng/Java/tree/master/StatePattern

Reference

Head First Design Pattern