You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/State Pattern.md
+5-2Lines changed: 5 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -14,9 +14,10 @@ The **State Pattern** allows and object to alter its behavior and when its inter
14
14
To truly understand the power of the State Pattern, let's look at a classic mechanical device: the **Gumball Machine**.
15
15
16
16
> [!QUESTION] What is a Gumball Machine?
17
-
A Gumball Machine is a coin-operated vending device commonly found in malls and arcades. It has a simple purpose: you give it a coin, and it gives you a round candy.
17
+
>A Gumball Machine is a coin-operated vending device commonly found in malls and arcades. It has a simple purpose: you give it a coin, and it gives you a round candy.
18
18
19
19
**How does it work?**
20
+
20
21
The user interaction is straightforward:
21
22
1.**Insert Coin:** You insert a quarter into the slot.
22
23
2.**Turn Crank:** You rotate the knob.
@@ -38,11 +39,13 @@ The complete state flow is visualized below:
38
39
[Note: Ensure this image displays the transition diagram between states]
39
40
40
41
**How the States Flow:**
42
+
41
43
The machine begins in the No Quarter state, waiting for a customer. When a coin is inserted, it transitions to the Has Quarter state. From here, if the user turns the crank, the machine usually moves to the Sold state to dispense candy. However, we also have a "lucky" feature: sometimes, the machine transitions to a Winner state, awarding two gumballs.
42
44
43
45
After dispensing, the machine checks its inventory. If gumballs remain, it resets to **No Quarter**. If the inventory is empty, it transitions to **Out of Gumballs**, where it ceases to accept coins until refilled.
44
46
45
47
**Why not use switch or if-else?**
48
+
46
49
A naive implementation might use a massive conditional structure (e.g., if (state == HAS_QUARTER) ...). However, this leads to spaghetti code. Every time we add a new state (like "Winner"), we would have to modify every single method in the class, violating the Open/Closed Principle. The State Pattern solves this by encapsulating behavior within specific state classes.
47
50
48
51
---
@@ -225,7 +228,7 @@ class GumballMachine {
225
228
```
226
229
227
230
The `SoldOutState` represents the machine when it is empty. In this state, the machine is effectively locked. It rejects coins and turning the crank does nothing.
0 commit comments