1. The State mode allows an "object" to change its behavior when its internal state changes.
2. Status mode roles:
Abstract state, specific State (usually several, with different behaviors under each State), environment (context) role (that is, the state of an object, generally, this object needs to initialize a state, change the state, and behavior in this state)
When we play basketball, athletes can be in normal, abnormal, and extraordinary states. Now we will take the status when we play basketball as an example,
First, we abstract the state and its behavior,
Interface State {
Public void shot ();
}
Then implement the specific state. Here we have three and three States.
Abnormal
Public class nonormalstate implements State {
Public void shot (){
System. Out. println ("Today you shot ten times ");
}
}
Normal:
Public class normalstate implements State {
Public void shot (){
System. Out. println ("Today you shot five in ten ");
}
}
Extraordinary:
Public class superstate implements State {
Public void shot (){
System. Out. println ("You shot ten shots today ");
}
}
At this time, we come to an environment where an athlete is normal.
Public class player {
Private state = new normalstate ();
Public void setstate (State state ){
This. State = State;
}
Public void shot (){
State. Shot (); // here I feel like an Object Adapter IN THE create mode. This should be the case,
}
}
Test this example
Public class statetest
{
Public static void main (string [] ARGs ){
Player player = new player ();
Player. Shot (); // shooting normally
Player. setstate (New nonormalstate ());
Player. Shot (); not shooting normally
Player. setstate (new superstate ());
Player. Shot (); shooting under extraordinary circumstances
}
}