状态模式
当一个对象的内在状态发生变化时改变其行为,这个对象看起来像是改变了其类。
State
package com.hml.state; public interface State { public void handle(Context c); }
ConcreteStateA
package com.hml.state; public class ConcreteStateA implements State{ public void handle(Context c) { c.setState(new ConcreteStateB()); } }
ConcreteStateB
package com.hml.state; public class ConcreteStateB implements State{ public void handle(Context c) { c.setState(new ConcreteStateA()); } }
Context
package com.hml.state; public class Context { private State state; public State getState() { return state; } public void setState(State state) { System.out.println(state.getClass().getName()); this.state = state; } public Context(State state) { super(); this.state = state; } public void request() { state.handle(this); } }
Test
package com.hml.state; public class Test { public static void main(String[] args) { Context c = new Context(new ConcreteStateA()); c.request(); c.request(); c.request(); c.request(); c.request(); } }
类图
状态模式的好处是将于特定状态相关的行为局部化,并且将不同的状态的行为分割开来。当一个对象的行为取决于他的状态时,并且必须在运行时刻根据状态改变行为时就可以考虑使用状态模式。