State mode of design mode
State mode, also known as the state object pattern (pattern of Objects for States), state mode is the behavior pattern of the object. State mode allows an object to change its behavior when its internal state changes. This object looks like it has changed its class.
Example: A person laughs when he is happy (laughs), cries (Tears of joy), and laughs when he is unhappy (a wry smile) and cries (weeping). First edition: Complete the function in the simplest way
Public classPerson {PrivatePersonstate State; PublicPerson (personstate state) { This. State =State ; } Public voidchangestate (personstate state) { This. State =State ; } Public voidSmile () {if(state = =personstate.happy) {System.out.println (Laugh); } Else if(state = =personstate.unhappy) {System.out.println (Wry smile); } } Public voidcry () {if(state = =personstate.happy) {System.out.println ("The joy of weeping."); } Else if(state = =personstate.unhappy) {System.out.println ("Crying and weeping."); } } }enumpersonstate {HAPPY, unhappy}
View Code
Test
Public Static void Main (string[] args) { new person (personstate.happy); P.smile (); P.cry (); P.changestate (personstate.unhappy); P.smile (); P.cry ();}
View Code
OK, the problem is solved, the person can laugh and cry in Happy and unhappy to show a different state, the problem comes, one is not only happy and unhappy two states, such as normal people will also laugh (smile) will Cry (tears), at this time to respond to this state, You can only modify the code of the person class!
Version two: decoupling
Abstract the state of a person
Public Interface personstate { void smile (); void cry ();}
View Code
Cry and laugh when you are happy
Public class Implements personstate { @Override publicvoid smile () { System.out.println (" Laughter "); } @Override publicvoid Cry () { System.out.println ("Joy and Cry");} }
View Code
Cry and laugh when you are not happy
Public class Implements personstate { @Override publicvoid smile () { System.out.println (" Wry Smile "); } @Override publicvoid Cry () { System.out.println ("weep bitterly");} }
View Code
Person
Public classPerson {PrivatePersonstate State; PublicPerson (personstate state) { This. State =State ; } Public voidchangestate (personstate state) { This. State =State ; } Public voidSmile () {state.smile (); } Public voidcry () {state.cry (); }}
View Code
Test
Public class Test { publicstaticvoid main (string[] args) { new personhappystate (); New Person (happy); P.smile (); P.cry (); New personunhappystate (); P.changestate (unhappy); P.smile (); P.cry (); }}
View Code
OK, then add normal state when crying, laugh is very simple, just implement Personstate interface, realize their own smile and cry method.
State mode of design mode