1 CSC 450 Slides adapted from slides created by Robert B. France State Models.
-
Upload
charlene-wright -
Category
Documents
-
view
220 -
download
0
Transcript of 1 CSC 450 Slides adapted from slides created by Robert B. France State Models.
1
• CSC 450
Slides adapted from slides created by Robert B. France
State Models
2
State Models A state model specifies the life histories of
objects in terms of the sequences of operations that can occur in response to external stimuli. For example, a state model can describe how an object
responds to a request to invoke one of its methods. A state model consists of state diagrams that
each describes how an object responds to external stimuli.
A state diagram describes behavior in terms of sequences of states that an object can go through in response to events.
3
Simple Example: Telephone Object
Idle
Active
lift receiver/ get dial tone
caller hangs up / disconnect
state
event
Activity that is performed during transition: it executes instantaneously
initial state
• When the object is created, it moves into the Idle state.
• If a “lift receiver” event is received the object moves from the Idle to the Active state. During the transition the “get dial tone” activity is executed.
• If a “caller hangs up” event occurs when in Active state, the object moves to the Idle state and the “disconnect” activity is performed during the transition.
4
Key Concepts An event is a significant or noteworthy
occurrence at a point in time. Examples of events: sending a request to invoke a
method, termination of an activity. An event occurs instantaneously in the time scale of
an application. A state is a condition of an object during its
lifetime. For example, a student is in the registered state after
completing course registration. A state is an abstraction of an object’s attribute values
and links For example, a bank account is in the Overdraft state
when the value of its balance attribute is less than 0.
5
Key Concepts - 2 A transition occurs when an event causes an
object to change from its current (source) state to a target state. For example, if a student is in the registered state and
then drops out of the program then the student is in the “not registered” state.
The source and target states can be the same. A transition is said to fire when the change from source
to target state occurs. A guard condition on a transition is a boolean
expression that must be true for a transition to fire
An activity is a behavior that is executed in response to an event.
6
top
Basic UML State Diagram
ReadyReady
stop
/ctr := 0stop
StateState
EventEvent
ActivityActivity
Initial state
Initial state
TransitionTransition
Final stateFinal state
DoneDone
“top” state“top” state
7
Guards Conditional execution of transitions
guards (Boolean predicates) must be side-effect free
SellingSelling
UnhappyUnhappy
HappyHappy
bid [(value >= 100) & (value < 200)] /sell
bid [value >= 200] /sell
bid [value < 100] /reject
8
Event Types ChangeEvent: Occurs when a condition expressed as a boolean
expression becomes true. when condition
Examples: when(temperature > 80); when(balance < 0)
SignalEvent: Occurs when an signal is sent or received, where a signal is a one-way transmission of information from one object to a target object. Event(param1,param2,…)
Examples: lift receiver; hang-up telephone
TimeEvent: Passage of a specific period of time after a designated event, or an occurrence of a specified time instance. Passage of time since entry to current state - after (time period) ,
e.g., after (10 secs), after (5 secs since exit of state A) Occurrence of a time instance – when(due-date=Feb 28, 2005,
11pm)
9
Object Behavior - General Model Typical object lifecycle
HandleRequest
HandleRequest
initializeObject
initializeObject
TerminateObject
TerminateObject
Wait forRequest
Wait forRequest
void:offHook (); {busy = true; obj.reqDialtone(); … };
Handling depends on specific request type
Handling depends on specific request type
10
Object Behavior and State Machines Reflecting object lifecycle in a state diagram
HandleEvent
InitializeObject
TerminateObject
Wait forEvent
on
off
Lamp On
Lamp On
Lamp Off
Lamp Off
off
on/print(”on”)
stop
11
anActiveObject
#currentEvent : Event
+ start ( )+ poll ( )+ stop ( )
Active Objects and State Diagrams
created
ready
start/^master.ready()
poll/^master.ack()
stop/
poll/defer
ready
created
start start/^master.ready() ready
If object is in the created state and a start event occurs, it sends a method invocation event (request to invoke ready()) to the object named master and moves to state ready.
12
Active Objects: Dynamic Semantics
Run-to-completion model: • Events are queued• An object processes events in a queue one at a
time.• An object cannot suspend handling of an event to
handle another event
ActiveObject:
13
Active1Active1 Active2Active2
The Run-to-Completion Model A high priority event for (another) active object
will preempt an active object that is handling a low-priority event on a uniprocessor
hi
hi
lo
Event is queued because object is handling the lo event
Object, Active1, has its activity suspended so that the Active2 object can respond to hi
14
15
State Representations
StateName
StateNameAtt1 : Attrib1
entry/action
exit/action
event/action
do/action
activity executed when state is entered
activity executed when state is exited
activity executed when event occurs while in state
activity executed while in state
16
State Syntax
A state symbol can have one or more compartments (all optional): Name compartment Internal transition compartment
contains internal actions or activities Format: event(args) [condition] / action entry / action (invoked implicitly) exit / action (invoked implicitly) do / machine name (invokes a nested state
machine)
17
State Syntax
Entry and exit activities cannot have arguments and cannot have guard conditions.
Activity expressions can use object attributes and links, and parameters of events on incoming transitions.
18
State Entry and Exit Actions
LampOnLampOn
entry/lamp.on();
exit/lamp.off();
e1
e2
19
Resulting activity sequence:printf(“exiting”);printf(“to off”);lamp.off();
Resulting activity sequence:printf(“exiting”);printf(“to off”);lamp.off();
Order of Actions: Simple Case
printf(“exiting”);printf(“needless”);lamp.off();
printf(“exiting”);printf(“needless”);lamp.off();
off/printf(“needless”);
off/printf(“to off”);LampOffLampOff
entry/lamp.off();
exit/printf(“exiting”);
LampOnLampOn
entry/lamp.on();
exit/printf(“exiting”);
20
Internal Transitions
Self-transitions that bypass entry and exit actions
LampOffLampOff
entry/lamp.off();
exit/printf(“exiting”);
off/null;
Internal transitiontriggered by an “off” event
Internal transitiontriggered by an “off” event
21
ErrorError
entry/printf(“error!”)
State (“Do”) Activities
Forks a concurrent thread that executes until: the action completes or the state is exited through an outgoing transition
do/while (true) alarm.ring();
“do” activity“do” activity
22
Static Conditional Branching Merely a graphical shortcut for convenient
rendering of decision trees
[(value >= 100) & (value < 200)] /sell
[value >= 200] /sell
[value < 100] /reject
SellingSelling
UnhappyUnhappy
HappyHappy
bid
23
bid /gain := calculatePotentialGain(value)
SellingSelling
UnhappyUnhappy
HappyHappy
Dynamic Conditional Branching Choice pseudostate: guards are evaluated at the
instant when the decision point is reached
[(gain >= 100) & (gain < 200)] /sell
[gain >= 200] /sell
[gain < 100] /reject
DynamicchoicepointDynamic
choicepoint
24
Hierarchical State Machines Graduated attack on complexity
states decomposed into state machines
LampFlashingLampFlashingflash/
1sec/1sec/
FlashOffFlashOff
entry/lamp.off()
FlashOnFlashOn
entry/lamp.on()off/
LampOffLampOff
entry/lamp.off()
LampOnLampOn
entry/lamp.on()
on/
on/on/
25
“Stub” Notation Notational shortcut: no semantic
significance
LampFlashingLampFlashingflash/
on/
FlashOn
FlashOff
off/
LampOffLampOff
entry/lamp.off()
LampOnLampOn
entry/lamp.on()
on/ on/
26
LampFlashingLampFlashing
1sec/1sec/
FlashOffFlashOff
entry/lamp.off()
FlashOnFlashOn
entry/lamp.on()off/
LampOffLampOff
entry/lamp.off()
LampOnLampOn
entry/lamp.on()
on/
Group Transitions Higher-level transitions
flash/
on/
Default transition tothe initial state in LampFlashing
Default transition tothe initial state in LampFlashing
Group transition: when on occurs in any LampFlashing state
a transition is made to LampOn
Group transition: when on occurs in any LampFlashing state
a transition is made to LampOn
27
Completion Transitions Triggered by a completion event
generated automatically when an immediately nested state machine terminates
CommittingCommitting
Phase1Phase1
Phase2Phase2CommitDoneCommitDone
completion transition (no trigger)
completion transition (no trigger)
28
LampFlashingLampFlashing
off/
FlashOffFlashOff
FlashOnFlashOn
Triggering Rules Two or more transitions may have the same
event trigger innermost transition takes precedence event is discarded whether or not it triggers a transition
on/
on/
29
State Syntax - Submachines
State name:submachine submachine is the name of a (nested) state machine
that has an initial and final state. Execution of the nested machine begins in the initial
state. When final state of the nested machine is reached then
the exit action of the parent state is executed (if it exists).
Dispense cash: Cash Dispenser
30
UML 2.0: Entry/Exit Points Encapsulation of submachines
definition of exit point
ReadAmountSM
selectAmount
EnterAmount
ok
abort
aborted
amount
otherAmount
abort
againdefinition of
entry point
31
Entry/Exit Points: Usage
VerifyCard
OutOfService
acceptCard
ReleaseCardVerifyTransaction
outOfService
releaseCard
ReadAmount :ReadAmountSM
aborted
use of exit point
use of entry point
rejectTransaction
again
ATM
32
Deferred Events Events can be retained if they do not trigger a
transition The event is put to the top of the queue; it must be
handled in the next event handling cycle
off/
LampOnLampOn
entry/lamp.on()
on/
LampOffLampOff
entry/lamp.off()
off/defer
Deferred eventDeferred event
33
Order of Actions: Complex Case Same approach as for the simple case
S1exit/exS1
S1exit/exS1
S11exit/exS11
S11exit/exS11
S2entry/enS2
S2entry/enS2
S21entry/enS21
S21entry/enS21
initS2E/actE
Actions execution sequence:
exS11 exS1 actE enS2 initS2 enS21
34
Composite States
A state can be decomposed in two ways: AND decomposition: object state decomposed
into two parallel components. OR decomposition: object state decomposed into
a network of states.
35
Orthogonality Multiple simultaneous perspectives on the same entity
Child
Adult
Retiree
age
Poor
Rich
financialStatus
36
Orthogonal Regions Combine multiple simultaneous descriptions
Child
Adult
Retiree
age
Poor
Rich
financialStatus
Poor
Rich
financialStatus
Child
Adult
Retiree
age
37
OutlawOutlaw
LawAbidingLawAbiding PoorPoor
RichRich
financialStatuslegalStatus
Orthogonal Regions - Semantics All mutually orthogonal regions detect the same events and
respond to them “simultaneously” usually reduces to interleaving of some kind
robBank/ robBank/
38
Catch-22
“There was only one catch and that was Catch-22, which specified that a concern for one's safety in the face of dangers that were real and immediate was the process of a rational mind. Orr was crazy and could be grounded. All he had to do was ask; and as soon as he did, he would no longer be crazy and would have to fly more missions. Orr would be crazy to fly more missions and sane if he didn't, but if he was sane he had to fly them. If he flew them he was crazy and didn't have to; but if he didn't want to he was sane and had to.” – Joseph Heller
39
Catch22Catch22sanityStatus flightStatus
Interactions Between Regions Typically through shared variables or awareness
of other regions’ state changes
(flying)/
Crazyentry/sane := false;
Crazyentry/sane := false;
Saneentry/sane := true;
Saneentry/sane := true;
requestGrounding/
Flyingentry/flying := true;
Flyingentry/flying := true;
Groundedentry/flying := false;
Groundedentry/flying := false;
(sane)/
(~sane)/
sane : Booleansane : Boolean
flying : Booleanflying : Boolean
40
Transition Forks and Joins For transitions into/out of orthogonal
regions:
StaffMember
StaffMember
employee
ChildChild AdultAdult RetireeRetiree
age
ManagerManager
41
Common Misuse of Orthogonality Using regions to model independent objects
Child
Adult
Retiree
Child
Adult
Retiree
Person1 Person2
Person1 Person2
42
An Example
43
Subsystem design modeling wrap-up What model should we start developing first?
Interaction model then class model Interaction models helps determine class responsibilities Focus first on interaction models that realize use cases
Class model and interaction model in parallel When should we use state and activity models
Use state models if system is reactive A reactive system maintains an ongoing interaction with its
environment. Air traffic control system Programs controlling mechanical devices such as a train, a plane. Ongoing processes such as a nuclear reactor.
Use activity models to define class methods
44
State Model Exercises
Develop a state machine for a Hotel Reservation system.
Develop a state machine for a student record system.
45
______________________Devon M. Simmonds
Computer Science Department
University of North Carolina Wilmington
_____________________________________________________________
Qu es ti ons?
The End
46
State Model exercise Complete state machine for a student record system.
Applicant Acceptedaward [accepted] /
Rejected
award [rejected] reapply
Registered
register
addCourse
addCourse
Dismissed
program-terminated
reapply
Graduateprogram-completed
Inactiveunregistered
register
after: one semester
no-reapplication
no-reapplication
award-presented
Active
47
State Model exercise Develop a state machine for a Hotel
Reservation system.
Input Bookingbooking request
Reservationreservation request
Cancellation
cancellation request
success
cancellation request query
transaction complete query
query query