源自
State模式
允许一个对象在其状态改变时改变它的行为看起来对象似乎修改了它的类
例子
view plaincopy to clipboardprint?
public interface State {
public void handle(Context ctx);
}
public class Context {
private State _state;
public Context(State state) {
_state = state;
}
public void request() {
if (_state != null) {
_statehandle(this);
}
}
public void ChangeState(State s) {
if (_state != null) {
_state = null;
}
_state = s;
}
}
public class ConcreteStateA implements State {
public void handle(Context ctx) {
Systemoutprintln(handle by ConcreteStateA);
if (ctx != null) {
ctxChangeState(new ConcreteStateB());
}
}
}
public class ConcreteStateB implements State {
public void handle(Context ctx) {
Systemoutprintln(handle by ConcreteStateB);
if (ctx != null) {
ctxChangeState(new ConcreteStateA());
}
}
}
public class StateClient {
public static void main(String[] args) {
State state = new ConcreteStateA();
Context context = new Context(state);
contextrequest();
contextrequest();
contextrequest();
contextrequest();
}
}