用途
状态模式是一种
行为型模式。
结构
![](https://i-blog.csdnimg.cn/blog_migrate/47754f2fe3f0e484dcc5e4b29f44c0a4.png)
图-状态模式结构图
State : 定义一个接口以封装与 Context 的一个特定状态相关的行为。
abstract
class State {
public abstract void Handle(Context context);
}
public abstract void Handle(Context context);
}
ConcreteState : 每一个子类实现一个与 Context 的一个状态相关的行为。
class ConcreteStateA
extends State {
@Override
public void Handle(Context context) {
context.SetState( new ConcreteStateB());
}
}
class ConcreteStateB extends State {
@Override
public void Handle(Context context) {
context.SetState( new ConcreteStateA());
}
}
@Override
public void Handle(Context context) {
context.SetState( new ConcreteStateB());
}
}
class ConcreteStateB extends State {
@Override
public void Handle(Context context) {
context.SetState( new ConcreteStateA());
}
}
Context : 维护一个 ConcreteState 子类的实例,这个实例定义当前的状态。
class Context {
private State state;
public Context(State state) {
this.state = state;
}
public void SetState(State state) {
this.state = state;
System.out.println("当前状态:" + state.getClass().getName());
}
public State GetState() {
return state;
}
public void Request() {
state.Handle( this);
}
}
private State state;
public Context(State state) {
this.state = state;
}
public void SetState(State state) {
this.state = state;
System.out.println("当前状态:" + state.getClass().getName());
}
public State GetState() {
return state;
}
public void Request() {
state.Handle( this);
}
}
测试代码
public
class StatePattern {
public static void main(String[] args) {
Context c = new Context( new ConcreteStateA());
c.Request();
c.Request();
}
}
public static void main(String[] args) {
Context c = new Context( new ConcreteStateA());
c.Request();
c.Request();
}
}
运行结果
当前状态:ConcreteStateB
当前状态:ConcreteStateA
当前状态:ConcreteStateA