在状态模式(State Pattern)中,类的行为是基于它的状态改变的。
允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
this.state = state;
}
public State getState(){
return this.state;
}
}
public interface State {
public void doAction(Context context);
}
public class StartState implements State {
@Override
public void doAction(Context context) {
System.out.println("start state");
context.setState(this);
}
}
public class StopState implements State {
@Override
public void doAction(Context context) {
System.out.println("stop state");
context.setState(this);
}
}
public class StateDemo {
public static void main(String[] args){
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
StopState stopState = new StopState();
stopState.doAction(context);
}
}