Java Implementation State mode
/*** @ Author stone */public class WindowState {private String stateValue; public WindowState (String stateValue) {this. stateValue = stateValue;} public String getStateValue () {return stateValue;} public void setStateValue (String stateValue) {this. stateValue = stateValue;} public void handle () {/** perform different operations based on different statuses, and then switch the status */if ("window ". equals (stateValue) {switchWindow (); this. stateValue = "full screen";} else if ("full screen ". equals (stateValue) {switchFullscreen (); this. stateValue = "window" ;}} private void switchWindow () {System. out. println ("switch to window status");} private void switchFullscreen () {System. out. println ("switch to full screen ");}}
/*** Status use * @ author stone **/public class WindowContext {private WindowState state; public WindowContext (WindowState state) {this. state = state;} public WindowState getState () {return state;} public void setState (WindowState state) {this. state = state;} public void switchState () {this. state. handle ();}}
/** State mode: behavior mode * not only changes the object State, but also changes the behavior of the object * According to the State, change Behavior */public class Test {public static void main (String [] args) {/** there are only two status values in this example, the status value can also be controlled by the Status class * by the client */WindowContext context = new WindowContext (new WindowState ("window"); context. switchState (); context. switchState (); context. switchState (); context. switchState ();}}
Print
Switch to window status switch to full screen status switch to window status switch to full screen status