Intention
Allows an object to change its behavior when its internal state changes. The object appears to have modified its class.
public class State { private String value; Public String GetValue () { return value; } public void SetValue (String value) { this.value = value; } public void Method1 () { System.out.println ("Execute the first opt!"); } public void Method2 () { System.out.println ("Execute the second opt!"); } }
public class Context { private state State; Public Context { this.state = state; } Public State getState () { return state; } public void SetState (state state) { this.state = state; } public void Method () { if (State.getvalue (). Equals ("State1")) { state.method1 (); } else if ( State.getvalue (). Equals ("State2")) { state.method2 (); } }
public class Test {public static void Main (string[] args) {state state = new State (); Context context = new context (state); Set the first state state.setvalue ("State1"); Context.method (); Set the second state state.setvalue ("State2"); Context.method (); }
Transferred from: http://blog.csdn.net/zhangerqing/article/details/8245537
Java Learning Note-design mode 21 (state mode)