State mode
First, the definition:
Allows change of behavior when an object's internal state changes, implementing state changes
Second, the role
The main solution is that when the conditional expression of a state transition is too complex, the judgment of the state is transferred to a series of classes of different states, simplifying the complex judgment.
Three, class diagram:
Iv. Realization OF
The 1.work class is used to implement the transformation state, state judgment, and the program that runs the corresponding state is also the interface that the user calls.
Public classWork {State state ; PublicWork () { This. State =NewFornoon (); } Private inthour; Public intGethour () {return This. hour; } Public voidSethour (inthour) { This. Hour =hour; } Public voiddoWork () { This. State.dowork ( This); } Public voidsetState (state state) { This. State =State ; }}
View Code
2.state class actual operation, call the work of the state switch
Public Abstract class State { publicabstractvoid doWork;}
View Code
Implementation class of 3.state
Public classAfternoonextendsState {@Override Public voiddoWork (Work work) {if(Work.gethour () > 12) {System.out.println ("In the Afternoon"); } Else{work.setstate (NewFornoon ()); Work.dowork (); } }} Public classFornoonextendsState {@Override Public voiddoWork (Work work) {if(Work.gethour () < 12) {System.out.println ("In the Morning"); } Else{work.setstate (Newafternoon ()); Work.dowork (); } }}
View Code
4. Customer Class Test class
Public class Client { publicstaticvoid main (string[] args) { new work (); Work.sethour (+); Work.dowork (); Work.sethour (+); Work.dowork (); }}
View Code
Design pattern Start-state mode