abstract class State {
public abstract void Handle(Context 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());
}
}
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);
}
}
public class StatePattern {
public static void main(String[] args) {
Context c = new Context(new ConcreteStateA());
c.Request();
c.Request();
}
}
当前状态:ConcreteStateB
当前状态:ConcreteStateA