Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give me a real-life, non-trivial use of the State Pattern

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!

like image 707
Joe Avatar asked Sep 22 '10 11:09

Joe


People also ask

What is state pattern example?

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.

What is state pattern used for?

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.


2 Answers

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.

like image 200
David Avatar answered Sep 29 '22 20:09

David


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.

like image 23
Vivek Goel Avatar answered Sep 29 '22 20:09

Vivek Goel