在狀態模式中,一個類的行為基于它的狀態的改變而改變。狀態模式歸屬于行為型模式。
在下面的實例中,我們創建了一個接口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