I'm looking for an example of where the State design pattern has been used to solve or simplify interesting or complicated state transitions. There are plenty of examples with three or four simple states. But what about code from real life projects that have sub-states and more than a handful of transitions? The kind of code that actually motivates use of the pattern. Bonus points pointers to code!
Example. The State pattern allows an object to change its behavior when its internal state changes. This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc.
The state pattern is used in computer programming to encapsulate varying behavior for the same object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.
One real-life use of State Pattern I have seen so far is in a Video Player capable of playing online video.
You have to handle playing, paused, buffering, connecting, seeking and even other states.
When the player is in playing or paused states, it is responsive to user interaction events.
When the player is in "connecting" state, it might not have enough data to know the video duration and so the seek bar should be disabled.
Once the player is connected, it will move to buffering state. In buffering state, the user can seek, or stop the video. But if he tries to pause or play the video, the command is saved for later, so that when the buffering is done, the video is either paused or start playing. etc.
Traffic Light System (time triggered | sensor [event] triggered)
States: RED, YELLOW, GREEN (simplest example)
Transitions: After a timer change RED to GREEN, GREEN to YELLOW, and YELLOW to RED.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With