📘 Scenario:
In the neon-lit city of Neo Aegis, stealth drones patrol government facilities. Each drone (the Context) operates in three distinct modes:
As events occur—like seeEnemy()
, hearNoise()
, enemyInRange()
, or loseEnemy()
—the drone’s behavior shifts accordingly.
⚠️ Problem:
if-else
or switch
logic clutters the code.💡 State Pattern Solution:
Each drone mode is encapsulated as a separate class implementing a common State
interface.
The drone switches its internal currentState
dynamically based on real-time input.
This keeps state-specific logic modular, extensible, and easy to maintain.
🖥️ Output:
[PatrolState] Guard is patrolling the area. [PatrolState] Intruder spotted! Switching to ALERT state. [AlertState] Guard is taking cover and surveying the area. [AlertState] Target in range! Switching to ATTACK state. [AttackState] Guard is engaging the enemy aggressively. [AttackState] Target escaped! Switching to PATROL state. [PatrolState] Guard is patrolling the area.