Java Magazine, July/August 2018
ORACLE COM JAVAMAGAZINE JULY AUGUST 2018 75 patterns public void goOutside display You are already in the hallway To see the other states check out the online codebase Conclusion The State pattern is a good one It sorts out the state specific behavior making it easier to read and maintain than having a long conditional statement in each method Its also easier to add new states Finally it makes the state transitions explicit inside the Context class and the States and they can be completely invisible to the outside Transitions are also atomic because only a single variable in the Context class typically with a name like currentState is changed on a transition Try the State pattern the next time you find yourself writing parallel if statements in several methods or anytime an objects behavior has to change significantly based on what state its in Youll like the improvement in readability and maintainability that it brings article Ian Darwin @ Ian_ Darwin has done all kinds of development from mainframe applications and desktop publishing applications for UNIX and Windows to a desktop database application in Java to healthcare apps in Java for Android Hes the author of Java Cookbook and Android Cookbook both from OReilly He has also written a few courses and taught many at Learning Tree International
You must have JavaScript enabled to view digital editions.