一句话总结
状态和行为
内容
状态模式的核心是状态和行为的绑定,不同状态对应不同的行为。
场景
订单状态的变化;电梯的变化
类图
代码示例
//环境类
public class Context {
public static final State STATE_A = new ConcreteStateA();
public static final State STATE_B = new ConcreteStateB();
// 默认状态A
private State currentState = STATE_A;
{
STATE_A.setContext(this);
STATE_B.setContext(this);
}
public void setState(State state) {
this.currentState = state;
this.currentState.setContext(this);
}
public State getState() {
return this.currentState;
}
public void handle() {
this.currentState.handle();
}
}
// 抽象状态:State
public abstract class State {
protected Context context;
public void setContext(Context context) {
this.context = context;
}
public abstract void handle();
}
//具体状态类
public class ConcreteStateA extends State {
@Override
public void handle() {
System.out.println("StateA do action");
// A状态完成后自动切换到B状态
this.context.setState(Context.STATE_B);
this.context.getState().handle();
}
}
//具体状态类
public class ConcreteStateB extends State {
@Override
public void handle() {
System.out.println("StateB do action");
}
}
public class Test {
public static void main(String[] args) {
Context context = new Context();
context.setState(new ConcreteStateA());
context.handle();
}
}
源码
无
网友评论