-
Notifications
You must be signed in to change notification settings - Fork 0
State

Behavioral pattern
Encapsulates object's behavior, which is based on its current state into separate classes, thus getting rid of monstrous if-else statements all across the class. Each condition branch is encapsulated into separate ConcreteState class.
State is being stored inside of a Context class field and that field value might change during object's lifecycle. These changes could be performed by ConcreteState classes on their own (if state diagram is more dynamic), or in Context itself (if state diagram will not change over time).
Advantages:
+ Encapsulates each branch of if/else conditions into separate state class, thus making Context class more maintainable and flexible.
+ Since each one of these states implement the same interface State, we can add new type of states freely without need to change Context class.
At this project we have the following model:
CdPlayer - interface, which represents musical CD player. Has the following methods:
-
startPlaying() - Turns the music on.
-
stopPlaying() - Turns the music off.
-
insertCD(cd : CD) - Inserts CD into CDPlayer
-
extractCD() : CD - Extracts CD from CDPlayer
If we imagine CDPlayer it could have the following states:
-
No cd inserted
-
Cd is inserted, but we did not start the player
-
Cd is inserted, and the player has started
And from there it is obvious that from the state #1 you cant call method startPlaying because there is nothing to play. And there is no point to attempt to call insertCD for state #2 and #3.
Logic how all these CDPlayer methods will work in different states can be encapsulated into different states:
-
NoCdState - code representation for #1
-
InsertedCdState - code representation for #2
-
PlayingCdState - code representation for #3
Besides logic itself, i also placed state transition logic into these states to make it more extendable.
For example, if we call insertCd method on CdPlayer object while it is in NoCdState appropriate method of NoCdState will change CdPlayer object state to InsertedCdState.
Attempts to call methods, that are illegal to current state (for example extractCd when we are in NoCdState) will result in an runtime exception being thrown.
Such structure will allow us to add more possible states to our CdPlayer without changing a line inside of it.