23种设计模式之状态模式
状态模式(State):当一个对象的内在状态改变时,允许改变其行为,这个对象看起来像是改变了其类。
package designMode.state; class Context { private State state; public Context(State state) { this.state = state; } /** * 对请求做处理,并设置下一状态 */ public void request(){ state.handle(this); } /***************getter&setter****************************/ public State getState() { return state; } public void setState(State state) { this.state = state; System.out.println("当前状态:"+state.getClass().getSimpleName()); } }
package designMode.state; interface State { void handle(Context context); }
package designMode.state; class ConcreteStateA implements State{ @Override public void handle(Context context) { context.setState(new ConcreteStateB()); } } class ConcreteStateB implements State{ @Override public void handle(Context context) { context.setState(new ConcreteStateA()); } }
package designMode.state; class Test { public static void main(String[] args) { Context c = new Context(new ConcreteStateA()); c.request(); c.request(); c.request(); c.request(); } }