状态模式:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了它的类。
public interface State {
public void handle(Context context);
}
public class Context {
private State state;
public Context(State state) {
this.state = state;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
System.out.println("当前状态:" + state.getClass().getSimpleName());
}
public void request() {
state.handle(this);
}
}
public class ConcreteStateOne implements State {
@Override
public void handle(Context context) {
context.setState(new ConcreteStateTwo());
}
}
public class ConcreteStateTwo implements State {
@Override
public void handle(Context context) {
context.setState(new ConcreteStateOne());
}
}
public class StateDemo {
public static void main(String[] args) {
Context context = new Context(new ConcreteStateOne());
context.request();
context.request();
context.request();
}
}