State mode: different states and actions; or, each State has a corresponding action.
When to use
: The state mode is usually used in actual use and is suitable for "state switching". Because we often use if elseif else for status switching,
If such a switchover occurs repeatedly, we need to think about whether the State mode can be used.
In the normal mode, we need to judge the action based on the status, and use a series of IF... else statements, for example:
Enum papercolor {
White, black, blue, red
}
Class mypaper
{
Papercolor;
Public mypaper (papercolor color ){
This. papercolor = color;
}
Public papercolor getmypapercolor (){
Return
This. papercolor;
}
}
Public class mainclass
{
Public static void main (string []
ARGs)
{
Mypaper = new
Mypaper (papercolor. White );
If (mypaper. getmypapercolor () = papercolor. White ){
System. Out. println ("You need a black pen ");
} Else
If (mypaper. getmypapercolor () = papercolor. Black ){
System. Out. println ("You need a white pen ");
} Else
If (mypaper. getmypapercolor () = papercolor. Blue ){
System. Out. println ("You need a red pen ");
} Else
If (mypaper. getmypapercolor () = papercolor. Red ){
System. Out. println ("You need a blue pen ");
}
}
}
Running result:
You need a black pen
White Paper requires a black pen, black paper requires a white pen, blue paper requires a red pen, red paper requires a blue pen .....
From the above program, as long as there are many kinds of paper, you need to have many else. If there are other colors of paper in the future, you must add the type in the enumeration and continue to add else if
Then re-compile the code. Obviously, this code is very unfavorable for future expansion. We can solve this problem using the state mode.
Interface papercolor {
Public void getpencolor ();
}
Class white implements papercolor
{
Public void
Getpencolor (){
System. Out. Print ("You need a black pen ");
}
}
Class black implements papercolor
{
Public void
Getpencolor (){
System. Out. Print ("You need a white pen ");
}
}
Class blue implements papercolor
{
Public void
Getpencolor (){
System. Out. Print ("You need a red pen ");
}
}
Class red implements papercolor
{
Public void
Getpencolor (){
System. Out. Print ("You need a blue pen ");
}
}
Class mypaper
{
Papercolor;
Public mypaper (papercolor color ){
This. papercolor = color;
}
Public papercolor getmypapercolor (){
Return
This. papercolor;
}
Public void choicepen (){
This. papercolor. getpencolor ();
}
}
Public class mainclass
{
Public static void main (string []
ARGs)
{
Papercolor color = new blue ();
Mypaper = new mypaper (color );
Mypaper. choicepen ();
}
}
Running result:
You need a red pen
The State mode not only makes the program easy to expand, but also eliminates the cumbersome if... else statement.