Look at the big talk design pattern of small partners, all know that the demo code in the design mode is not Java, for programming, design patterns are not limited to any language, is about the idea of programming.
Today I read this article again, read the other People's blog on the design of the understanding of the pattern, hoping to draw some of the core of the idea, the unexpected is to see a lot of blog on the state pattern understanding may be some deviation.
Normally, if there is no State mode, we will use a bunch of if else if or switch case to handle. Find the right entrance! Such code violates a single principle, and future maintenance will be reaching.
The use of State mode can solve this problem very well, to see the class diagram
Liar design mode-Class diagram
Take a look at the simple author's example:
/***/Publicinterface State {publicvoid Writeprogram (work work);}
/*** Context*/ Public classWork {PrivateState state ; PrivateInteger Hour; PublicWork () { state=Newgoodmorning (); } Public voidWriteprogram () {state. Writeprogram ( This); } PublicInteger Gethour () {returnhour; } Public voidSethour (Integer hour) { This. Hour =hour; } Public voidsetState (state state) { This. State =State ; }}
/** * One branch of the state of the morning */ public class GoodMorning implements state{@Override Span style= "COLOR: #0000ff" >public void Writeprogram { if (Work.gethour () < 12" else {work.setstate ( new aftermorning ()); Work.writeprogram (); } }}
/** */ public class aftermorning implements state {@Override Span style= "COLOR: #0000ff" >public void Writeprogram { if (Work.gethour () < 14 "a bit Sleepy" else {work.setstate ( new Evening ()); Work.writeprogram (); } }}
/***/Publicclassimplements state { @Override Public void Writeprogram (Work work ) { if (Work.gethour () >=) { System.out.println ( "It's time to get off the clock."}}}
The above is the author's understanding of the state mode, if the requirements are changed, add some state, we only need to increase the subclass, if it is in the middle of the insert State, we only need to change the point of a state to be able to.
Hope can help learning State mode of small partners, do not mechanically design patterns, understand the essence of the most important!!!
Java State mode (Liar design mode)