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 5 of 5

Enumerating the possible states
It may be desirable occasionally to enumerate all of the possible states. For example, you might want to write a loop, where the loop index is one of the possible states. It's not common that you want to do such a thing, but it's possible. To do this, the various State objects need links to one another, and the State class needs to define a method that returns an Enumeration object, which lets you iterate over the linked list of defined states. The mechanisms for doing that are defined in "Creating enumerated constants in Java."

Conclusion

The State pattern is a good addition to your bag of programming tricks, because it is so useful. There are many ways to implement the actions associated with state transitions. It is possible to define actions as part of transition-objects, or define them as part of state-objects. You can have behaviors that occur when exiting a state, when entering a state, or both. The emerging Unified Modeling Language standard (UML) allows for all three. In this article, you learned how to use the fundamental O-O concept of polymorphism to implement a version of the State pattern that associates actions with states and that allows both state-exit and state-enter actions. You also saw how to completely encapsulate the state transitions in a state object that can be owned by a higher-level "containing" class.

About the author

Eric Armstrong has been programming and writing professionally since before there were personal computers. His production experience includes AI programs, system libraries, real-time programs, and business applications in a variety of languages. He is currently writing a book on a soon-to-be-released Java IDE.
  • Print
  • Feedback

Resources