Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

How to implement state-dependent behavior

Doing the State pattern in Java

  • Print
  • Feedback

Page 2 of 5

The following "precerpt," from The JBuilder Java Bible (due to be published this fall), describes how to implement the State pattern in Java.

Understanding the State pattern

The State pattern is useful when you have an object that can be in one of several states, with somewhat different behavior in each state. For example, when a car's RPMs are in the "power band," then the car's acceleration is much quicker than when the revolutions per minute are outside that range. The Car object might have a state variable that indicates "in the power band," "below the power band," or "above the power band." The acceleration characteristics of the car would then depend on its current state.

There are many cases in which an object's behavior depends on its current state. For example, when you're sleepy, it's hard to think. But when you're jazzed on coffee and chocolate, it can be easy! The examples go on and on. So it's worthwhile to have a readily usable State pattern to draw on.

The way the State pattern works is shown in the following diagram:

  • Print
  • Feedback

Resources