状态机
场景
行为根据状态改变
代码
实现方案1
环境类控制状态转移
Sample1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| interface State{ void action(); }
class StateA implements State { public void action() { } }
class StateB implements State { public void action() { } }
class Context { private State state; private int value;
public void setState(State state) { this.state = state; }
public State getState() { return state; }
public void request() { state.action(); checkState(); }
private void checkState() { if(value = 0) { this.setState(new StateA()); }else if(value = 1) { this.setState(new StateB(); } } }
|
实现方案2
状态内控制状态转移,状态之间有依赖
Sample1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| interface State{ void action(Context context); }
class StateA implements State { public void action(Context context) { context.setState(new StateB()); } }
class StateB implements State { public void action(Context context) { context.setState(new StateA()); } }
class Context { private State state;
public void setState(State state) { this.state = state; }
public State getState() { return state; }
public void request() { state.action(this); } }
|
优缺点
- 避免了在多个方法内大量if-else判断各种状态
- 状态可扩展性强
- 增加了类个数,复杂度上升
应用