Java Magazine, July/August 2018
ORACLE COM JAVAMAGAZINE JULY AUGUST 2018 70 patterns With the State defined I now define the four states by subclassing Because the app needs only one instance of each State class the classes are instantiated as anonymous classes and saved as fields However if your program changes state only rarely you could create the State subclasses as named classes configure them in the constructor and lazily instantiate the State subclass only when switching into it Here is the code for the Stopped State subclass which defines how the various operations will be performed when invoked while the player is in the stopped state In this example stop is some low level hardware control method that might stop a motor moving on a DVD player The commented out setIcon call symbolizes some update to the GUI State stoppedState new State @ Override public void enterState stop setIcon Icon stopped @ Override public void stop Do nothing already stopped @ Override public void start currentState playingState currentState enterState
You must have JavaScript enabled to view digital editions.