在状态模式中,一个类的行为基于它的状态的改变而改变。状态模式归属于行为型模式。
在下面的实例中,我们创建了一个接口State,定义了一个操作方法,两个实现类StartState和StopState。另外,创建了一个上下文类Context,这个类关联到State类。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
53
|
//状态类 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()); } } |
输出结果
1
2
3
4
5
6
7
|
Player is in start state Start State Player is in stop state Stop State |
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/man_embedded/article/details/50402072