STATE
PATTERNS
Team “CODINO”:
142140
142064
142053
142001
Allows an object to alter its
behavior when its internal state
changes. The object will appear to
change its class.
State Patterns
Definition
State diagram for Gumball
matching
Coding's for Gumball
matching class
Coding’s for Gumball
testing class
Output
What will happened if
change request?
New State Diagram
Code will be changed as…
The New
Design…
1. First, define a State interface that
contains a method for every action in
the Gumball Machine.
2. Then, implement a state class for every
state of machine. These classes will be
responsible for behavior of the machine
when it in the corresponding state.
3. Finally, get rid of all of our conditional
code instead delegate to the state
class to do the work for us.
Defining the state
interfaces and classes
Behavior in each class
when action is called
Reworking the Gumball
Machine
Complete Gumball
Machine class
Implementation of state
classes
Gumball 1 in 10 game
Output
Refill the Gumball Machine
Differences between State
and Strategy
• Client usually specifies the
strategy object that the context is
composed with. While the pattern
provides the flexibility to change
the strategy object at runtime,
there is typically one strategy
object that is most appropriate for
the context object.
State
• Set of behavior encapsulated in
state objects; at any time the
context is delegating to one of
those state. Over time, the current
states changes across the set of
state objects to reflect the
internal state of the context, so
the context’s behavior changes
over time. Client knows very little,
if anything, about the state
objects.
Strategy
• Alternative to putting lots of
conditional in your context:
you can simply change the
state object in the context to
change it’s behavior!
• Flexible alternative to sub
classing: if you use
inheritance to define the
behavior of a class, you can
stuck with it even if you
need to change it. With
strategy you can change the
behavior by composing with
different objects!
State patterns

State patterns