Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 10. State Design Pattern > Design Pattern to Create a State Machine

10.1. Design Pattern to Create a State Machine

The State design pattern focuses on the different states in an application, transitions between states, and the different behaviors within a state. Looking at a simple light switch application, we can see two states, On and Off. In the Off state, the light is not illuminated, and in the On state, the light illuminates. Further, the light switch transitions from the Off state to the On state using a method that changes the application's state—flipping the switch. Likewise, it transitions from On to Off with a different transition and method. An interface holds the transitions, and each state implements the transitions as methods unique to the state. Each method is implemented differently depending on the context of its use. So, a method, illuminateLight(), for example, would do one thing in the Off state and something entirely different in the On state, even though illuminateLight() method is part of both states.

10.1.1. Key Features

The following key features characterize the State design pattern:

  • States exist internally as part of an object.

  • Objects change in certain ways when states change. Objects may appear to change classes, but they're changing behavior that is part of the class.

  • Each state's behavior depends on the current state of other states in the object.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial