java 设计模式之State(状态模式)
在状态模式中,一个类的行为基于它的状态的改变而改变。状态模式归属于行为型模式。
在下面的实例中,我们创建了一个接口State,定义了一个操作方法,两个实现类StartState和StopState。另外,创建了一个上下文类Context,这个类关联到State类。UML类图如下所示:
//状态类 public interface State { public void doAction(Context context); } //实现类StartState.java 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"; } } //实现StopState.java 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"; } } //上下文Context.java 实际运用时可自行更改 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()); } }
输出结果
Player is in start state Start State Player is in stop state Stop State
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!