Skip to content

Commit 2a67880

Browse files
Corrected some mistakes
1 parent fa980bc commit 2a67880

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

content/State Pattern.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,10 @@ The **State Pattern** allows and object to alter its behavior and when its inter
1414
To truly understand the power of the State Pattern, let's look at a classic mechanical device: the **Gumball Machine**.
1515

1616
> [!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.
1818
1919
**How does it work?**
20+
2021
The user interaction is straightforward:
2122
1. **Insert Coin:** You insert a quarter into the slot.
2223
2. **Turn Crank:** You rotate the knob.
@@ -38,11 +39,13 @@ The complete state flow is visualized below:
3839
[Note: Ensure this image displays the transition diagram between states]
3940

4041
**How the States Flow:**
42+
4143
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.
4244

4345
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.
4446

4547
**Why not use switch or if-else?**
48+
4649
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.
4750

4851
---
@@ -225,7 +228,7 @@ class GumballMachine {
225228
```
226229

227230
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.
228-
```
231+
```java title="SoldOutState.java"
229232
class SoldOutState implements State {
230233
private final GumballMachine gumballMachine;
231234

0 commit comments

Comments
 (0)