状态
状态是行为设计模式之一,其中类的行为根据其状态而变化。
关键概念:
上下文:行为根据状态变化的类/对象
状态:抽象状态
具体状态:代表各种状态,它改变context类的行为。
让我们通过一个例子来理解这一点:
state.java
public interface state { public void doaction(context context); }
国家具体实施
public class startstate implements state { private context context; public startstate(){} @override public void doaction(context context){ this.context = context; this.context.setstate(this); system.out.println("player is in startstate"); } public string tostring(){ return "start state"; } } public class endstate implements state { private context context; public endstate(){} @override public void doaction(context context){ this.context = context; this.context.setstate(this); system.out.println("player is in endstate"); } public string tostring(){ return "end state"; } }
主要
public class main { public static void main(string args[]){ context context = new context(); state state = new startstate(); state.doaction(context); //current state system.out.println(context.getstate().tostring()); state state2 = new endstate(); state2.doaction(context); //new state system.out.println(context.getstate().tostring()); } }
输出:
Player is in StartState Start State Player is in EndState End State
注意:以上代码遵循isp、lsp、srp、ocp的扎实原则
以上就是状态的详细内容,更多请关注其它相关文章!