State mode, which changes behavior through state changes.
// Environment Class
public class Context {
// The two states switch to each other
public static final State STATE1 = new ConcreteState1();
public static final State STATE2 = new ConcreteState2();
// Current status
private State currentState;
// Get the current status
public State getCurrentState() {
return currentState;
}
// Set current state and environment objects
public void setCurrentState(State currentState) {
this.currentState = currentState;
this.currentState.setContext(this);
}
// Behavior Method 1, Delegate to Status Object
public void handle1(){
this.currentState.doSomething1();
}
// Behavior Method 2, Delegate to Status Object
public void handle2(){
this.currentState.doSomething2();
}
}
// Abstract state
public abstract class State {
// Environmental Role
protected Context context;
// Setting up environment roles
public void setContext(Context context){
this.context = context;
}
// Behavior method
public abstract void doSomething1();
public abstract void doSomething2();
}
// Specific state object, state 1 case handled, state 2 case handled by environment class
public class ConcreteState1 extends State {
@Override
public void doSomething1() {
// Business logic handled by this state itself
}
@Override
public void doSomething2() {
// Set the current state to 2 and leave it to context
super.context.setCurrentState(Context.STATE2);
super.context.handle2();
}
}
// Specific state objects, state 2 cases handled, state 1 cases handed over to the environment class
public class ConcreteState2 extends State {
@Override
public void doSomething1() {
// Set the current state to 1 and leave it to context
super.context.setCurrentState(Context.STATE1);
super.context.handle1();
}
@Override
public void doSomething2() {
// Business logic handled by this state itself
}
}
// Test Class
public class Test {
public static void main(String[] args) {
// Environment Class
Context context = new Context();
// Set the current state to state1
context.setCurrentState(new ConcreteState1());
// The execution of the corresponding method is accompanied by a state transition, which is hidden
context.handle1();
context.handle2();
}
}
Scenarios where behavior changes with state, such as permission designs, where a person's state varies even if the same behavior is performed, require consideration of using state mode.
Using switch or if judgment statements extensively in programs can lead to unclear program structure and confusing logic. The use of state mode can avoid this problem very well. It achieves conditional judgment processing by extending subclasses.