Java Magazine, July/August 2018
ORACLE COM JAVAMAGAZINE JULY AUGUST 2018 72 patterns In this example invalid but harmless operations are silently ignored because thats how real media players work Obviously there will be some cases where it makes sense to signal invalid usage for example by logging or throwing an exception You need to ensure that the variable containing the state can never be null in my example I use a field initialization to ensure that this is set from the beginning State currentState stoppedState While this way of doing things may seem like more code than the maze of if statements shown earlier in fact it is slightly longer by line count it is worthwhile in terms of moremaintainable code You can more clearly see what goes where and just as important the compiler will probably tell you if you forgot to write a required method for a particular state due to the interface requirement that all methods be implemented There are several possible variations to how you The State pattern sorts out the state specific behavior making it easier to read and maintain the code and easier to add new states implement the pattern Depending on the scope of the application it might be useful to move the interface to be a noninner class of the Context and have the Context class also implement the interface so the compiler will check that all the delegation methods are present with the correct arguments and return types The State classes themselves dont have to be inner classes at all If it made sense they could be separate package level visibility classes the Context class could create them Here the Context would typically pass a reference to itself into the constructor for example State shuttingDownState new ShuttingDownState this This is because the State classes are likely to need access to nonpublic methods and fields in the Context class
You must have JavaScript enabled to view digital editions.