How to implement the State design pattern in Java?
The state pattern is a type of behavioral design pattern that allows an object to change its behavior when its internal state changes. In the state pattern, an object’s behavior is determined by its state.
Below is a simple implementation of the State Pattern.
- Define a state interface (State) that declares the behavior methods of an object.
- Each concrete state class that implements the state interface has its own implementation of the methods defined in the state interface.
- Hold a state object in the context that can switch between different states.
- Provide a method in the context class (e.g. setState) to toggle the state.
- In the context class, call the corresponding action method based on the current state.
Here is a simple Java code implementation:
// 定义状态接口
interface State {
void doAction(Context context);
}
// 实现具体状态类
class StartState implements State {
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
}
class StopState implements State {
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}
}
// 上下文类
class Context {
private State state;
public Context() {
state = null;
}
public void setState(State state) {
this.state = state;
}
public State getState() {
return state;
}
}
// 测试代码
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
StopState stopState = new StopState();
stopState.doAction(context);
}
}
When running the above code, the output will be:
Player is in start state
Player is in stop state
In the example above, the State interface defines a behavior method doAction, and the StartState and StopState are concrete state classes that each implement the doAction method. The Context class holds a state object that can switch between different states. In the test code, we first create a Context object, then create a StartState object and use the doAction method to switch the Context object’s state to StartState; then create a StopState object and use the doAction method to switch the Context object’s state to StopState.