The core idea is: when the state of the object changes, at the same time change its behavior, very good understanding! Take QQ, there are several states, online, stealth, busy, and so on, each state corresponds to different operations, and your friends can see your state, so, the state mode is two points: 1, you can change the state to obtain different behavior. 2. Your friends can see your changes at the same time. Look at the picture:
Package statetest;/** * The core class of the status class * @author Administrator * */public class State {private string Value;public string Getvalu E () {return this.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!");}}
Package statetest;/** * Status mode toggle class * @author Administrator * */public class Context {Private state state;public context State) {this.state=state;} Public State getState () {return this.state;} public void SetState (String value) {this.state=state;} public void Method () {if (State.getvalue (). Equals ("State1")) {state.method1 ();} if (State.getvalue (). Equals ("State2")) {state.method2 ();}}}
Package Statetest;public class Test {public static void main (string[] args) {//TODO auto-generated method Stubstate State = new State (); Context Context=new context (state);//Set the first status State.setvalue ("State1"); Context.method ();//Set the second state State.setvalue (" State2 "); Context.method ();}}
Output:
Execute the first opt!
Execute the second opt!
According to this feature, the state pattern in the daily development with a lot of, especially to do the site, we sometimes want to according to a certain property of the object, to distinguish some of their functions, such as simple permissions control.
Status mode (state)