概念
在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。
在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。
设计
根据context上下文中的状态,来区分行为。
代码
public interface State {
void doAction();
}
public class StartState implements State{
@Override
public void doAction() {
System.out.println(this.getClass().getName());
}
}
public class StopState implements State{
@Override
public void doAction() {
System.out.println(this.getClass().getName());
}
}
public class StateContext {
// true代表开始 false代表结束
private boolean state;
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
}
public class DoState {
public static void doState(StateContext context){
if(context.isState()){
// 开始状态
StartState ss = new StartState();
ss.doAction();
return;
}
// 结束状态
StopState ss = new StopState();
ss.doAction();
}
}
public class MainState {
public static void main(String[] args) {
StateContext context = new StateContext();
context.setState(true);
// 开始状态
DoState.doState(context);
// 结束状态
context.setState(false);
DoState.doState(context);
// 结果:
// teststatepattern.StartState
//teststatepattern.StopState
}
}