Using system;
Namespace Pattern {///
Private myState State = NULL;
Public void execute () {// Execute State Dothing DT = New Dothing (state); dt.execute (); // Switch State Swich (state) {Case MyState.hungry: State = MyState.Adry; Case MyState.adry: state = myState.TIRE; case myState.TIRE: state = myState.OK; case myState.OK:.. state = myState.HUNGRY;}}} public class DoThing {private myState state = null; DoThing (myState svalue) {state = Svalue;} public void execute () {SWICH (this.State) {Case MyState.hungry: console.writeline ("Eating"); Case MyState.adry: console.writeline ("Drink Water"); Case MyState.Tire : Console.writeline; Case MyState.ok: console.writeline ("Continue Travel");}}}
It can be seen from the above. The changes are directly affected. The things to have occurred. And the state is constantly changing. If it is not a simple assignment, it is necessary to do a lot of complex work. For example, POP Situation of the STPCONECTION STD statement seems to be cumbersome. Maybe you will say a write function, but the situation is not universal. It does not meet the object-oriented principle. Yes, we still have to do it to kick the switch. Because We have reason to believe that we have better ways to solve problems. We can see by the above. State is determined by a state manager and status itself. So. Therefore, how is the manager to manage more State. That is to say, the state must be abstract. In other words, it is to solve the problem using an interface or abstract class. * / Public enum myState {Hungry, adry, Tire, OK};
public interface ImyState {void Execute (StateManager sm); myState getState ();} public class Hungry_State: ImyState {public void Execute (StateManager sm) {// switch to the next state sm.setState (new ADRY_State ()); Console. WriteLine ( "food");} public myState getState () {return myState.HUNGRY;}} public class ADRY_State: ImyState {public void Execute (StateManager sm) {// switch to the next state sm.setState (new ADRY_State () ); Console.writeline ("drinking water");} public myState getState () {return myState.adry;}} public class Tire_State: iMyState {public void execute (stateManager sm) {// Switch to the next state sm.setState (New adry_state ()); console.writeline ("Rest");} public myState getState () {return myState.tire;}} public class ok_state: iMyState {public void execute (stateManager sm) {// Switch to the next State Sm.setState (New Adry_State ()); Console.Writeline ("Continue Travel");} public myState getState () {return myState.ok;}} public class stateManager}} public class stateManager} PUBLIC VOID SETSTATE (IMYSTATE IMS) {ms = IMS;} public void execute () {ms.execute (this);}}
}