O'Reilly logo

Design Patterns Java™ Workbook by Steven John Metsker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 STATE pattern can help you to simplify this code. To apply STATE in this example, make each state of the door a separate class, as Figure 22.3 shows.

Figure 22.3. This diagram shows a door's states as classes in an arrangement that mirrors the door's state machine.

The refactoring that Figure 22.3 shows uses the Door_2 class to contain the context of the state machine. A ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required