- Forward


The State Pattern
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • State charts are often used to describe dynamic behavior
  • The "traditional" way to implement state transitions often involves complicated, nested if statements
An Example
Back SMYC Forward

A Statechart Diagram for a Simplified Garage Door Opener

garage-door-opener_states
An Example (cont.)
Back SMYC Forward

A "Messy" Implementation

javaexamples/statepattern/alternative/Controller.java
 
An Important Example
Back SMYC Forward
  • A "Real World" Statechart:
    • statechart_tcp
  • A Question:
    • How messy would the nested if statements be for this?
The State Pattern
Back SMYC Forward
  • Approach:
    • Delegate the responsibility of handling state transitions to encapsulations of the states
  • Participants:
    • An abstract State
    • Several concrete State classes
    • A Context
The State Pattern (cont.)
Back SMYC Forward

In UML:

state-pattern
The Example Revisited
Back SMYC Forward

Using the State Pattern

garage-door-opener_classes
The Example Revisited (cont.)
Back SMYC Forward

The Abstract State

javaexamples/statepattern/State.java
 
The Example Revisited (cont.)
Back SMYC Forward

The States

javaexamples/statepattern/AwaitingCombination.java
 
The Example Revisited (cont.)
Back SMYC Forward

The States (cont.)

javaexamples/statepattern/Closed.java
 
The Example Revisited (cont.)
Back SMYC Forward

The States (cont.)

javaexamples/statepattern/Locked.java
 
The Example Revisited (cont.)
Back SMYC Forward

The States (cont.)

javaexamples/statepattern/Opened.java
 
The Example Revisited (cont.)
Back SMYC Forward

The Context

javaexamples/statepattern/Controller.java
 
There's Always More to Learn
Back -