状态(State)模式的定义:对有状态的对象,把复杂的“判断逻辑”提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为。
public abstract class State {
public abstract void Handle(Context context);
}
public class ConcreteStateA extends State {
@Override
public void Handle(Context context) {
System.out.println("当前状态是 A.");
context.setState(new ConcreteStateB());
}
}
public class ConcreteStateB extends State {
@Override
public void Handle(Context context) {
System.out.println("当前状态是 B.");
context.setState(new ConcreteStateA());
}
}
public class Context {
private State state;
//定义环境类的初始状态
public Context() {
this.state=new ConcreteStateA();
}
//设置新状态
public void setState(State state) {
this.state=state;
}
//读取状态
public State getState() {
return(state);
}
//对请求做处理
public void Handle() {
state.Handle(this);
}
}
public class StatePatternClient {
public static void main(String[] args) {
Context context=new Context(); //创建环境
context.Handle(); //处理请求
context.Handle();
context.Handle();
context.Handle();
}
}