0% found this document useful (0 votes)
14 views47 pages

Lect 12

The document discusses encoding state machines, focusing on a simple elevator system and a turnstile check gate as examples. It outlines various methods for translating state machines into code, including doubly nested switches, state tables, and design patterns. Additionally, it covers interaction diagrams, particularly sequence diagrams, to model object interactions and behaviors in software design.

Uploaded by

ss649
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views47 pages

Lect 12

The document discusses encoding state machines, focusing on a simple elevator system and a turnstile check gate as examples. It outlines various methods for translating state machines into code, including doubly nested switches, state tables, and design patterns. Additionally, it covers interaction diagrams, particularly sequence diagrams, to model object interactions and behaviors in software design.

Uploaded by

ss649
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 47

Encoding State

Machines
Lecture 12
06-03-2025

1
Exercise : Simple Elevator System
(Partial)

The elevator is by default on the ground floor.

When idle and a button at a higher floor is
pressed:
 It moves up and halts when the requesting floor is
reached.


When idle and a button on a lower floor is pressed:
 It moves down. Halts when requesting floor is reached.


If inactive at a floor for more than 10 minutes:
 It moves down to the ground floor.

2
Simple Elevator System
Lift
Call

Lift
Call

Lift
Call

Lift
Call
3
Elevator: State Machine Representation

On Ground [H] Moving


Floor Button press Up
arrive
at floor
arrive
Moving to at floor
Ground Floor [H]
Button
press
arrive at
Moving floor Idle
Down [L]
Button press

[H] time-out H: Higher L: Lower


4
Encoding State Machine
Diagrams

5
Translating State Machine to Code


Complicacy:
 State machines have many concepts that
are not directly supported in
programming languages ---- neither
procedural nor OO languages, for
example:

States, events, transitions, composite
states, concurrent states, history, etc

6
General Idea: How to Generate Code?
Mapping State Model to Program Code

on
Initialize
Object
Lamp On
Wait for
Event on/display(”on”)
Handle
Event
off
off
Lamp
Off
Terminate
Object
stop

7
8
How to Encode an FSM?


Three main approaches:
 Doubly nested switch in loop

 State table

 State Design Pattern

9
3 Principal Ways

Doubly nested switch in loop:
 Scalar variables store state --- Used as switch
discriminator for first level switch
 Event type is discriminator in second switch
 Hard to handle concurrent states, composite state,
history, etc.


State table: Straightforward table lookup

Design Pattern:
 States are represented by classes
 Transitions handled by methods in classes
10
Doubly Nested Switch Approach
int state, event; /* state and event are variables */
while(TRUE){
switch (state){ /* Wait for event */
Case state1: switch(event){
case event1: state=state2; etc…; break;
case event2:…
default:… break;
}
Case state2:switch(event){…
…. }
}}

11
State Table Approach

From the state machine, we can set up a state
transition table with a column for the actions
associated with each transition
Present Next
Event Actions
state state

e1 BTN_off none
BTN_off
e2 BTN_on set red LED flashing

e1 BTN_on none
BTN_on
e2 BTN_off reset red LED flashing
12
Turnstile: Exercise 2

A turnstile check gate would be installed
at a railway station.

When the turnstile is powered on:
 It starts in the locked state.

When a commutator drops a one rupee coin:
 The gate gets unlocked and a message “Gate Open”
appears.
 Exactly one person is allowed to pass through before
the gate gets locked.
 If more than one person try to pass through, an alarm
is sounded and gate gets locked.

Also when any one tries to jump over the gate:
 An alarm is started and gate is locked.
13
Turnstile Exercise cont…


When the alarm is ON:
 A message “Please wait: Gate temporarily blocked”
is displayed.
 If any one still inserts a coin, it returns the coin
without unlocking the gate.
 The alarm is reset when an attendant swipes a
card and the gate starts at the locked state.

When any one inserts a coin when the gate is
already open:
 The coin is returned.

If there is a power failure any time:
 The gate gets locked and “Power fail: inoperative”
message is displayed and coins are not accepted.14
Turnstile: First-Cut State Model

coin/ Unlock
Locked

Unlocke
jump/ Alarm pass/ Lock d
coin/Return coin

Alarm

15
Turnstile: Final State Model power
OFF
powerOFF
coin/return
powerO
N
Locke coin Unlock
d ed

cardSwipe pas
jum s
multiple
p Alarm pass||
Entry/
display
jump

16
enum State {Locked, Unlocked, Alarm, PowerOFF};
enum Event {Pass, Coin, multiplePass, jump,
cardSwipe};
static State s = Locked;
void Transition(Event e){
switch(s){
case Locked:
switch(e){
case Coin:
s = Unlocked;
Unlock();
C e break;
d
Co case Jump:
s=Alarm;
Alarm();
break;
} 17

break; cont…
case Unlocked:
switch(e){
case Coin: returnCoin();
break;
case Pass: s = Locked;
Lock();
break;
case jump:
case multiplePass: s=Alarm;
Alarm();
break;}
break;
case Alarm: …. … ….
18
public class Turnstile{
enum state{ Locked, Unlocked, Alarm}
public Turnstile(){ state=Unlocked;}
public pass(){
if(state== Unlocked) state=Locked;}
public coin(){
switch(state){
case Locked: state=Unlocked; break;
case Unlocked: returnCoin(); break;
}}
public jump(){…}
…}

19
Ex. 3: Course Registration Software

When a course is created, it is open for
registration, and number of students is made
0.

If the course is open and a student registers,
the student count incremented.

A course can be cancelled anytime:
 The registered students are notified and their
registration cancelled.


If registered student number reaches 100:
 The course is closed for registration, and it is
allocated a room and a time slot. 20
Exercise 3: State Transition Diagram
[ count < 100 ]
register student

create/ Open
count=0
entry: Register student
Increment count

Cancel/Notify
registered [ count = 100 ]/
students
Finalize course

Canceled
Cancel/ Closed
Notify
registered
students

21
Home Work: ATM

To withdraw money:
 customer inserts the ATM card.

Authentication is done by checking an
entered PIN.

If PIN is incorrect:
 Customer asked to enter PIN again
 On three unsuccessful attempts, the card is
seized and account is locked.

On correct entry amount requested is
dispensed and card ejected. 22
Home Work


How to handle code generation for
composite AND and OR states?


How to generate code for history
state?

23
24
Interaction Diagrams

25
What are Interaction Diagrams?


Can model the way a group of objects
collaborate to realize some behaviour.


How many interaction diagrams to draw for
a development project?
 Typically each interaction diagram realizes
behaviour of a single use case

 Draw one sequence diagram for each use


case.
26
Interaction Diagrams

Three kinds:
 Interaction overview diagram
 Sequence and Collaboration (now communication
diagram in UML 2.0) diagrams.


Sequence and Collaboration diagrams are actually
equivalent:
 But, portray different perspectives


As we shall see:
 These diagrams play a very important role in any
design process.
27
Interaction Overview Diagram


Focuses on the overview of the
flow of control of the interactions.

It is a variant of the Activity Diagram:
 Nodes are sequence diagrams.

 Describes the interactions where


messages and lifelines are hidden…

28
Interaction Overview Diagram


Each individual activity is pictured as a
frame:
 Can contain nested interaction diagrams.


Makes the interaction overview
diagram useful to deconstruct a
complex scenario:
 Otherwise would require multiple if-then-
else paths to be illustrated as a single
sequence diagram" 29
sd Withdrawal

ip
Sk
ref
Authenticate

PIN OK PIN NOK

sd sd
:User :ATM :Bank :User :ATM
withdraw
msg (“illegal entry”)
msg (“amount”)
amount (a) chkAcct (a)

sd sd
:User :ATM :Bank :User :ATM :Bank
enough bal
money not enough bal
msg(“amount too big”)
receipt

sd
:User :ATM
30
msg (“card”)
A First Look at Sequence Diagrams


Captures how objects interact with each
other:
 To realize some behavior.


Time ordering of messages. member:
LibraryMember book:Book :Book
Copy

ok = canBorrow()
borrow(book)

[ok] borrow(member) setTaken(member)


Can model:
 Simple sequential flow, branching,
iteration, recursion, and concurrency.
31 31
Simple Rule: Develop One Sequence
diagram for every use case

Return
Book member: book:Book :Book
LibraryMember Copy

Use ok = canBorrow()

Case borrow(book)

Borrow
Book [ok] borrow(member)

Search setTaken(member)
Book

32
32
Elements of a Sequence Diagram

: Customer : Order : Payment : Product : Supplier

object
place an order

process
Activation lifetime
validate

if ( payment ok )
if ( not in stock )
deliver
back order

get address

mail to addres
message
33
Example Cont…

: Customer : Order : Payment : Product : Supplier

place an order

process

validate
Sequence of message sending

if ( payment ok )
if ( not in stock )
deliver
back order

get address

mail to addres

34
An Example of A Sequence Diagram
:Library
:Library
:Library Book :Library
Book :Book
Boundary Renewal Member
Register
Controller

renewBook find MemberBorrowing


displayBorrowing
selectBooks bookSelected
* find
[reserved]
[reserved] apology
update
apology

confir
m

confirm
updateMemberBorrowing

35
Sequence Diagram for the renew book use case
Message Arrows for Communication

Message arrows represent the type of
communications between two objects in a
sequence diagram:
 Synchronous message :

Sending object suspends action and waits for the
response to the message
(filled head)
 Asynchronous message:

Sending object continues with its operations without
waiting for the response (open head)

 A return of control from the synchronous


message
 A creation of a new entity 36
Asynchronous Messages

An example of this is a Timer in Java:
 An object that implements ActionListener may
register itself as a listener for a Timer object
 The Timer object will store a handle to the object,
 Later, when the Timer expires, an event will be
issued to the object's 'actionPerformed' method


Obviously, if the object had to wait for the timer
to expire:
 It could have wasted a long period of potential
computation time. 37
timer = new Timer(ONE_SECOND, new TimerListener());
...
timer.start(); Example
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
progressBar.setValue(task.getCurrent());
if (task.done()) {
Toolkit.getDefaultToolkit().beep();
timer.stop();
startButton.setEnabled(true);
}
}
}

38
Asynchronous Messages Example

:ActionListener inv:Inventory

addActionListener(self:ActionListener)
Time

…continue operation…

The eventual
response is
actionPerformed(e: ActionEvent) called a callback

39
Return Values

Optional --- indicated using a dashed
arrow:
 Label indicates the return value.
 Don’t need when it is obvious what is
v
being returned, e.g. getTotal()


Model a return value only when you
need to refer to it elsewhere:
 Example: A parameter passed to
another message. 40 40
Summary of Kinds of Arrows

Procedure call or other kind of


nested flow of control
(The sender losses control until the
receiver finishes handling the
message)

Flat flow of control(The sender does


not expect a reply)

Return
(Unblocks a synchronous send)
41
Synchronous Messages

Flow of control, typically implemented as a
method call.
 The routine that handles the message is
completed before the caller resumes
execution.
:A :B
doYouUnderstand()

return
Caller (optional)
Blocked yes

42
Lifetime of objects

creation: arrow with
'new' or create written
above it
 Notice that an object
created, appears at
point of call.

deletion: an X at
bottom of object's
lifeline
 Java doesn't explicitly
delete objects; they
fall out of scope and 43
43
Method calls

Activation: thick box over object's life line;
drawn when object's method is already on the
stack
 Either that object is running its code, or it is
on the stack waiting for another object's
method to finish
 Nest to indicateActivation
recursion
:Controller

Nestin
g
Activation 44
Object Creation

An object may create another object via
a <<create>> message.

:A

<<create>>
:B

45
Object Destruction

An object may destroy another object via a
<<destroy>> message.
 An object may also destroy itself.


But, how do you destroy an object in Java?
 Avoid modeling object destruction unless memory
management is critical.

:A :B
<<destroy>>

46
Looping

Iteration example UML 1.x:

:CompoundShape :Shape
draw()
*draw()

47

You might also like