状态是行为设计模式之一,其中类型的行为根据其状态而变化。
关键概念:上下文:根据状态变化行为的类/对象状态:抽象状态具体状态:它代表各种状态,改变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原则
以上是状态的详细内容。请关注图灵教育的其他相关文章!