描述
状态模式就两点:1、可以通过改变状态来获得不同的行为。2、你的好友能同时看到你的变化。
思想
当对象的状态改变时,同时改变其行为
适用
状态模式在日常开发中用的挺多的,尤其是做网站的时候,我们有时希望根据对象的某一属性,区别开他们的一些功能,比如说简单的权限控制
UML

示例
1 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 42 43 44 45 46 47 48 49 50 51 52
| class State{ private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public void name(){ Test.printMsg("State.name"); } public void say(){ Test.printMsg("State.say"); } }
class Context{ private State state; public Context(State state) { this.state = state; } public State getState() { return state; } public void setState(State state) { this.state = state; } public void method() { if (state.getValue().equals("name")) { state.name(); } else if (state.getValue().equals("say")) { state.say(); } } }
public class Test { public static void printMsg(String msg){ System.out.println(msg); } public static void main(String[] args){ State state = new State(); Context context = new Context(state); state.setValue("name"); context.method(); state.setValue("say"); context.method(); } }
|