Java Magazine, July/August 2018
The State Pattern Elegantly manage state transitions without large switches or numerous if statements ORACLE COM JAVAMAGAZINE JULY AUGUST 2018 66 patterns Were all familiar even nonprogrammers implicitly with the notion of a state machine The machine is anything that can be in one of several discrete states with defined transitions A simple cofee machine can be only on or of The Start button turns it on Another button or a sensor of some kind turns it of It cannot be 72 on nor can it be in a state of making popcorn or playing music A media player whether implemented in hardware or software can be in any one of several states stopped paused playing or rewinding The Play button transitions from the stopped state to the playing state The Pause button transitions from the playing state to the paused state The Stop button transitions from either the playing or paused state to the stopped state The behavior of the buttons or Java methods is contextually dependent upon what state the machine is in Pressing Stop when the machine isnt doing anything is ignored Pressing Start when the machine is running also will usually be ignored Its common to diagram these transitions by using state diagrams similar to the one in Figure 1 Figure 1 is for a stateful device such as a media player but you can imagine the diagram would be similar for say 3D printer firmware and many other kinds of devices And the same general idea would apply for a graphics application which might have edit and preview modes states or for a computer game with player play computer play and won lost states The notion of a state machine gave rise to and gave its name to the State pattern In this pattern an object can be in exactly one of a fixed number of states and transition between them causes changes in the objects behavior IAN DARWIN
You must have JavaScript enabled to view digital editions.