
.avif)
A Real-World Analogy: Phone Notification Modes
Imagine you have a smartphone with multiple notification modes: Normal, Vibrate, and Silent. In Normal mode, incoming calls ring out loud. In Vibrate mode, the phone doesn’t ring but buzzes. In Silent mode, it neither rings nor vibrates — perhaps it just logs a missed call. You (the phone’s owner) might manually switch between these modes depending on context (at work, in a meeting, at the movies, etc.), and the phone’s behavior changes accordingly without you fiddling with the internals of how ringing works each time.
This scenario is a relatable analogy for the State pattern:
The Phone is the object whose behavior changes.
The current mode (Normal/Vibrate/Silent) is the internal state of the phone.
Each state defines how the phone should behave for certain actions (like receiving a call).
Switching modes is like changing the internal state object, which in turn changes the phone’s behavior.
Why not just use an if-else or enum? You could code the phone’s behavior with a simple if or switch: