Java设计模式 - 状态模式
在状态模式中,类行为基于其状态而改变。
状态模式是一种行为模式。
当使用状态模式时,我们创建各种状态对象和上下文对象,其行为随着其状态对象改变而变化。
例子
interface State {
public void doAction(Context context);
}
class StartState implements State {
public void doAction(Context context) {
System.out.println("In start state");
context.setState(this);
}
public String toString() {
return "Start State";
}
}
class StopState implements State {
public void doAction(Context context) {
System.out.println("In stop state");
context.setState(this);
}
public String toString() {
return "Stop State";
}
}
class PlayState implements State {
public void doAction(Context context) {
System.out.println("In play state");
context.setState(this);
}
public String toString() {
return "Play State";
}
}
class Context {
private State state;
public Context() {
state = null;
}
public void setState(State state) {
this.state = state;
}
public State getState() {
return state;
}
}
public class Main {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
System.out.println(context.getState().toString());
PlayState playState = new PlayState();
playState.doAction(context);
StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}
上面的代码生成以下结果。
In start state
Start State
In play state
In stop state
Stop State