|
9 | 9 | ---
|
10 | 10 |
|
11 | 11 | ## Also known as
|
| 12 | + |
12 | 13 | Objects for States
|
13 | 14 |
|
14 | 15 | ## Intent
|
15 |
| -Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. |
| 16 | + |
| 17 | +Allow an object to alter its behavior when its internal state changes. The object will appear to |
| 18 | +change its class. |
16 | 19 |
|
17 | 20 | ## Explanation
|
| 21 | + |
18 | 22 | Real world example
|
19 | 23 |
|
20 |
| -> When observing a mammoth in its natural habitat it seems to change its behavior based on the situation. It may first appear calm but over time when it detects a threat it gets angry and dangerous to its surroundings. |
| 24 | +> When observing a mammoth in its natural habitat it seems to change its behavior based on the |
| 25 | +> situation. It may first appear calm but over time when it detects a threat it gets angry and |
| 26 | +> dangerous to its surroundings. |
21 | 27 |
|
22 | 28 | In plain words
|
23 | 29 |
|
24 | 30 | > State pattern allows an object to change its behavior.
|
25 | 31 |
|
26 | 32 | Wikipedia says
|
27 | 33 |
|
28 |
| -> The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface. |
| 34 | +> The state pattern is a behavioral software design pattern that allows an object to alter its |
| 35 | +> behavior when its internal state changes. This pattern is close to the concept of finite-state |
| 36 | +> machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a |
| 37 | +> strategy through invocations of methods defined in the pattern's interface. |
29 | 38 |
|
30 | 39 | **Programmatic Example**
|
31 | 40 |
|
@@ -126,17 +135,23 @@ And here is the full example how the mammoth behaves over time.
|
126 | 135 | mammoth.observe();
|
127 | 136 | mammoth.timePasses();
|
128 | 137 | mammoth.observe();
|
129 |
| - |
130 |
| - // The mammoth gets angry! |
131 |
| - // The mammoth is furious! |
132 |
| - // The mammoth calms down. |
133 |
| - // The mammoth is calm and peaceful. |
| 138 | +``` |
| 139 | + |
| 140 | +Program output: |
| 141 | + |
| 142 | +```java |
| 143 | + The mammoth gets angry! |
| 144 | + The mammoth is furious! |
| 145 | + The mammoth calms down. |
| 146 | + The mammoth is calm and peaceful. |
134 | 147 | ```
|
135 | 148 |
|
136 | 149 | ## Class diagram
|
137 |
| - |
| 150 | + |
| 151 | + |
138 | 152 |
|
139 | 153 | ## Applicability
|
| 154 | + |
140 | 155 | Use the State pattern in either of the following cases
|
141 | 156 |
|
142 | 157 | * An object's behavior depends on its state, and it must change its behavior at run-time depending on that state
|
|
0 commit comments