Java Reference
In-Depth Information
case STAYOPEN :
return "StayOpen";
default :
return "Closed";
}
}
When a user clicks the carousel's one-touch button, the carousel generates a call to a Door
object's click() method. The Door_1 code for a state transition mimics the information in
Figure 22.1:
public void click()
{
if (state == CLOSED)
{
setState(OPENING);
}
else if (state == OPENING || state == STAYOPEN)
{
setState(CLOSING);
}
else if (state == OPEN)
{
setState(STAYOPEN);
}
else if (state == CLOSING)
{
setState(OPENING);
}
}
The setState() method of the Door_1 class notifies observers of the door's change:
private void setState(int state)
{
this.state = state;
setChanged();
notifyObservers();
}
CHALLENGE 22.2
Write the code for the complete() and timeout() methods of the Door_1
class.
Refactoring to State
The code for Door_1 is somewhat complex because the use of the state variable is spread
throughout the class. In addition, you might find it difficult to compare the state transition
methods, particularly click() , with the state machine in Figure 22.1. The S TATE pattern can
help you to simplify this code. To apply S TATE in this example, make each state of the door
a separate class, as Figure 22.3 shows.
Search WWH ::




Custom Search