状态模式
定义
当一个对象内在状态改变时允许其改变行为,这个对象看起来像改变了其类
代码
抽象状态
1 2 3 4 5 6 7 8 9 10 11
| public abstract class State { protected Context context;
public void setContext(Context context) { this.context = context; }
public abstract void handle1(); public abstract void handle2();
}
|
具体状态
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class ConcreteState1 extends State {
@Override public void handle1() { System.out.println("concrete state 1 handle1"); }
@Override public void handle2() { super.context.setCurrentState(Context.STATE2); super.context.handle2(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class ConcreteState2 extends State {
@Override public void handle1() { super.context.setCurrentState(Context.STATE1); super.context.handle1(); }
@Override public void handle2() { System.out.println("concrete state 2 handle2"); } }
|
环境角色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class Context { public final static State STATE1 = new ConcreteState1(); public final static State STATE2 = new ConcreteState2();
private State currentState;
public State getCurrentState() { return currentState; }
public void setCurrentState(State currentState) { this.currentState = currentState; this.currentState.setContext(this); }
public void handle1(){ this.currentState.handle1(); }
public void handle2(){ this.currentState.handle2(); }
}
|
测试
1 2 3 4 5 6 7 8 9 10
| public class ContextTest {
@Test public void testState(){ Context context = new Context(); context.setCurrentState(new ConcreteState1()); context.handle1(); context.handle2(); } }
|