Please enable JavaScript.
Coggle requires JavaScript to display documents.
State (Implementation (Table based alternative for each state table maps…
State
Implementation
-
Creating and destroying state objects 1) When states are known only at runtime and do not change frequently - then create the state objects when needed and destroy them after use.
2) When states change frequently, then create state objects ahead of time and do not destroy them
Who defines the state transitions? - Can be defined by the context object or each state can decide the next state to transition to
-
-
Consequences
It makes state transitions explicit. If states were represented as variables, then the state at any point would be an assigned variable, objects make the state explicit
State objects can be shared amongst different context objects if they have on instance variables and just behaviors
Localizes state specific behavior and partitions states for different behaviors. Avoids monolithic conditional behavior
Motivation
Ideal an object moves through a state machine with actions that move it from one state to another. Instead of using several if statements within a single method and having to modify the class whenever there is new state, this pattern can be used
Each state is represented by a separate class and the current state is delegated to the Context object. When the internal state of the context object changes, the current state is set to the appropriate state object
Applicability
An object's behavior depends on its state and its behavior should change at runtime depending on its state
Operations involve large multipart conditional statements that depend on the state.
The state is usually a set of enumerated constants
Multiple operations have the same the conditional structure
Each branch of the conditional structure can be represented as separate class and each object can vary independently of the other objects
-
Related Patterns
When state objects have just behavior and no instance variables, these become flyweights
-
Intent
Allow an object to alter its behavior when its internal state changes. The object appears to change its class.
-