Java implementation state pattern
State mode is a behavioral design pattern that allows an object to change its behavior when its internal state changes. State patterns encapsulate the behavior of objects in different state classes, allowing states to transition to each other, thereby achieving the goal of dynamically changing object behavior.
Applicable scenario:
When the behavior of an object depends on its state and needs to be changed at runtime based on the state, state mode can be considered.
When the behavior of an object is related to its state and state transitions are frequent, state patterns can be used to simplify the code.
Benefits:
1. Through state patterns, state related code can be encapsulated in state classes, making the code clearer and easier to maintain.
2. It is easier to extend the state class and add new states, which conforms to the Open–closed principle.
3. Separate the state and behavior of objects to make state transitions more controllable.
Below is a simple example code to demonstrate the implementation of state mode:
//State interface
interface State {
void doAction(Context context);
}
//Specific Status Class A
class StateA implements State {
public void doAction(Context context) {
System. out. println ("The current state is A");
context.setState(new StateB());
}
}
//Specific Status Class B
class StateB implements State {
public void doAction(Context context) {
System. out. println ("The current state is B");
context.setState(new StateA());
}
}
//Context class
class Context {
private State currentState;
public Context() {
currentState = new StateA();
}
public void setState(State state) {
currentState = state;
}
public void doAction() {
currentState.doAction(this);
}
}
//Test Code
public class Main {
public static void main(String[] args) {
Context context = new Context();
Context. doAction()// Output: The current state is A
Context. doAction()// Output: The current state is B
Context. doAction()// Output: The current state is A
}
}
In the above example code, the state pattern defines the behavior of the state through the 'State' interface, and the specific state class implements the 'State' interface and changes the state of the context object in the 'doAction' method. The context class' Context 'holds a reference to the current state, executes the behavior of the current state by calling the' doAction 'method, and transitions the state to the next state. In the test code, the transition process of the state can be seen based on the output.