Design Patterns Java™ Workbook

(Michael S) #1
Chapter 22. State

public void click()
{
door.setState(door.STAYOPEN);
}


public void timeout()
{
door.setState(door.CLOSING);
}
}


CHALLENGE 22.4


Write the code for DoorClosing.java.

The new design leads to much simpler code, but you might feel a bit dissatisfied that the
"constants" that the Door class uses are in fact local variables.


Making States Constant............................................................................................................................


Suppose that you decide to move the state constants to a DoorConstants interface. For this
approach to work, you have to eliminate the Door instance variable from the DoorState
class. You can drop this variable by changing the click(), complete(), and timeout()
transition methods in the DoorState class to require a Door object as an input parameter. In
this design, a Door object that receives, for example, a click() method from the carousel
forwards this call as state.click(this).

Free download pdf