Java Magazine, July/August 2018
ORACLE COM JAVAMAGAZINE JULY AUGUST 2018 68 patterns enum StateName STOPPED PLAYING PAUSED REWINDING StateName currentStateName Then I might define each of the four methods using logic like the following code Because lots of things work only in one or another state I need to check what state the object is in So I end up with a lot of if statements or a giant switch statement in each method public void start if currentStateName StateName STOPPED currentStateName StateName PLAYING startPlay else if currentStateName StateName PAUSED currentStateName StateName PLAYING resumePlay else if currentStateName StateName PLAYING System out println Already playing else if currentStateName StateName REWINDING System out println Wait a while OK I also need the same amount of conditional code in each of the four methods This becomes a serious maintenance issue when you need to add or change functionality And seriously whos ever worked on a project for a few months and not had to add a feature If youre not getting feature add requests you probably have no users The State pattern suggests a cleaner way to organize the code To refactor the previous approach using the State pattern Ill start by creating an interface called State and make four instances of it one for each state the player can be in First heres the interface interface State void stop
You must have JavaScript enabled to view digital editions.