Strategy Pa Ern and State Pa Ern: CSCI 3132 Summer 2011 1
Strategy Pa Ern and State Pa Ern: CSCI 3132 Summer 2011 1
Trade-os
Advantages
Eliminates
large
condi:onal
statements.
Easier
to
keep
track
of
dierent
behavior
because
they
are
in
dierent
classes.
A
variety
of
implementa:ons
for
the
same
behavior.
Disadvantages
Increases
the
number
of
objects.
All
algorithms
use
the
same
interface.
Example
I
water state variable
increaseTemp() decreaseTemp()
StateOfWater
increaseTemp() decreaseTemp()
WaterVapor Client
increaseTemp() increaseTemp() decreaseTemp()
LiquidWater
increaseTemp() decreaseTemp()
Ice
increaseTemp() decreaseTemp()
10
State
Pa*ern
Context class: Represents the interface to the outside world. State abstract class: Base class which defines the different states of the state machine. Derived classes from the State class: Defines the true nature of the state that the state machine can be in. Context class maintains a pointer to the current state. To change the state of the state machine, the pointer needs to be changed.
11
Example
II
MyMood state variable
doSomething()
MoodState
mad Client
doSomething()
angry
happy
doSomething()
doSomething()
doSomething()
12
13
14
Trade-os
Advantages
Encapsulates
all
behavior
of
a
state
into
an
object
Eliminates
massive
lines
of
code
involving
if/else
or
switch/case
statements
with
state
transi:on
logic
State
changes
occur
using
one
object,
therefore,
avoiding
inconsistent
states.
Disadvantages
15
16