Definition:
The gof design patterns define State patterns as: allowing an object to change its behavior when its internal state changes.
Let's take a look at an example:
Package com. State; <br/> public class kissingprincess {<br/> // flag, indicating whether it is a frog or a prince. <Br/> private Boolean isfrog = true; <br/> // perform different operations based on isfrog. <Br/> Public void greet () {<br/> If (isfrog) <br/> system. Out. println ("frog! "); <Br/> else <br/> system. Out. println (" Prince! "); <Br/>}< br/> // set isfrog to false. <Br/> Public void kiss () {<br/> isfrog = false; <br/>}</P> <p> // main function. <Br/> Public static void main (string [] ARGs) {<br/> kissingprincess Prince = new kissingprincess (); <br/> prince. greet (); <br/> prince. kiss (); <br/> prince. greet (); <br/>}< br/>}
Output result:
Frog!
Prince!
In this example, an isfrog variable is used to identify whether it is a frog or a prince. If it is a prince, output "Prince! "If it is a frog, the output is" frog !".
In this example, a friend's words are just "writing for entry-level programmers ". In Java, pay attention to the concept of object oriented programming.
If the status is large, many if else statements will be used, which is not only tedious and difficult to maintain, but also does not reflect the idea of forward to object programming.
After applying the status mode to the previous example, the following code can be changed:
Package COM. state; <br/> public class kissingprincess2 {</P> <p> private State state = new frog (); </P> <p> private interface state {<br/> void response (); <br/>}</P> <p> private class frog implements State {</P> <p> @ override <br/> Public void response () {<br/> system. out. println ("frog! "); <Br/>}</P> <p> private class Prince implements State {</P> <p> @ override <br/> Public void response () {<br/> system. out. println ("Prince! "); <Br/>}</P> <p> Public void greet () {<br/> state. response (); <br/>}</P> <p> Public void change (State state) {<br/> This. state = State; <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> kissingprincess2 PRINCE2 = new kissingprincess2 (); <br/> prince2.greet (); <br/> prince2.change (prince2.new Prince (); <br/> prince2.greet (); <br/>}< br/>}
Output result:
Frog!
Prince!
The above example is the basic idea of the state mode, and we hope readers will understand it carefully.
Here is an example of the State mode:
People who have played CS know that there are many guns in CS, such as AK47 and M16. But no matter what the guns are, after you pick them up, you can only trigger the trigger to take the bullets out. This is the same as our state mode idea, no matter how the underlying implementation (for example, whether it is frog or prince in the above example, and then perform different operations ), the outer interfaces remain unchanged (GREET method ).