场景如上:在一个方法中需要判断很多种情况,比如:上午12点之前:精神百倍,13点:饿了午饭,17点:下午状态不错,继续努力等等。正常情况我们是用好多if else 来做判断。
这样有两个弊端:
1.代码长度太长。
2.不利于维护,每次有情况变换需要考虑太多。
使用状态模式:
public interface State { public void doAction(Context context); }
public class StartState implements State { public void doAction(Context context) { System.out.println("Player is in start state"); context.setState(this); } public String toString(){ return "Start State"; } }
public class StopState implements State { public void doAction(Context context) { System.out.println("Player is in stop state"); context.setState(this); } public String toString(){ return "Stop State"; } }
public class Context { private State state; public Context(){ state = null; } public void setState(State state){ this.state = state; } public State getState(){ return state; } }
public class StatePatternDemo { public static void main(String[] args) { Context context = new Context(); StartState startState = new StartState(); startState.doAction(context); System.out.println(context.getState().toString()); StopState stopState = new StopState(); stopState.doAction(context); System.out.println(context.getState().toString()); } }