Java Reference
In-Depth Information
Chapter 22. State
The
state
of an object is a combination of the current values of its attributes. When you call a
set-
method, you typically change an object's state, and an object can change its own state
as its methods execute.
In some cases, an object's state can be a prominent aspect of its behavior, such as when
modeling transactions and machines. Logic that depends on the object's state may spread
through many of the class's methods. To counter this spread, you can move state-specific
behavior into a group of classes, with each class representing a different state. This lets you
avoid having deep or complex
if
statements, relying instead on polymorphism to execute
the right implementation of an operation. The intent of the S
TATE
pattern is to distribute
state-specific logic across classes that represent an object's state.
Modeling States
When you model an object whose state is important, you may find that you have a variable
that tracks how the object should behave, depending on its state. This variable may appear in
complex, cascading
if
statements that focus on how to react to the events that an object can
experience. One problem with this approach to modeling state is that
if
statements can
become complex. Another problem is that when you adjust how you model the state, you
often have to adjust
if
statements in several methods. The S
TATE
pattern offers a cleaner,
simpler approach, using a distributed operation.
Consider the Oozinoz software that models the state of a carousel door. A
carousel
is a large,
smart rack that accepts material through a doorway and stores the material according to a bar
code ID on the material. The door operates with a single button. If the door is closed, clicking
the button makes the door start opening. If you click again before the door opens fully, the
door will begin closing. If you let the door open all the way, it will automatically begin
closing after a 2-second timeout. You can prevent this by clicking again when the door is
open. Figure 22.1 shows the states and transitions of the carousel's door.