Design Pattern 简明教程
Design Patterns - State Pattern
在状态模式中,类行为会根据其状态而变化。这种设计模式属于行为模式。
In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern.
在状态模式中,我们创建表示各种状态的对象,以及随着其状态对象的变化而行为发生变化的上下文对象。
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.
Implementation
我们将创建一个定义操作的 State 接口和实现该 State 接口的具体状态类。Context 是一个承载 State 的类。
We are going to create a State interface defining an action and concrete state classes implementing the State interface. Context is a class which carries a State.
我们的演示类 StatePatternDemo 将使用 Context 和状态对象演示基于它所处状态的类型,Context 发生行为变化。
StatePatternDemo, our demo class, will use Context and state objects to demonstrate change in Context behavior based on type of state it is in.
Step 1
创建一个接口。
Create an interface.
State.java
public interface State {
public void doAction(Context context);
}
Step 2
创建实现相同接口的具体类。
Create concrete classes implementing the same interface.
StartState.java
public class StartState implements State {
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
public String toString(){
return "Start State";
}
}
StopState.java
public class StopState implements State {
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}
public String toString(){
return "Stop State";
}
}
Step 3
创建 Context 类。
Create Context Class.
Context.java
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
}
Step 4
使用 Context 查看状态改变时行为的变化。
Use the Context to see change in behaviour when State changes.
StatePatternDemo.java
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
System.out.println(context.getState().toString());
StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}