Lect 13
Lect 13
and OOAD
Lecture 13
11-03-2025
1
Elements of a Sequence Diagram
object
place an order
process
Activation lifetime
validate
if ( payment ok )
if ( not in stock )
deliver
back order
get address
mail to addres
message
2
Example Cont…
place an order
process
validate
Sequence of message sending
if ( payment ok )
if ( not in stock )
deliver
back order
get address
mail to addres
3
An Example of A Sequence Diagram
:Library
:Library
:Library Book :Library
Book :Book
Boundary Renewal Member
Register
Controller
confir
m
confirm
updateMemberBorrowing
4
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)
Obviously, if the object had to wait for the timer
to expire:
It could have wasted a long period of potential
computation time. 6
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);
}
}
}
7
Asynchronous Messages Example
:ActionListener inv:Inventory
addActionListener(self:ActionListener)
Time
…continue operation…
The eventual
response is
actionPerformed(e: ActionEvent) called a callback
8
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. 9 9
Summary of Kinds of Arrows
Return
(Unblocks a synchronous send)
10
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 (optiona
Blocke l)
d yes
11
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 12
12
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 13
Object Creation
An object may create another object via
a <<create>> message.
:A
<<create>>
:B
14
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>>
15
Looping
Iteration example UML 1.x:
:CompoundShape :Shape
draw()
*draw()
16
Exercise 0: Develop Sequence Diagram
A user can use a travel portal to plan a
travel
When the user presses the plan button, a
travel agent applet appears in his window
Once the user enters the source and
destination,
The travel agent applet computes the route
and displays the itinerary.
Then travel agent applet gets destroyed once
the user presses any key 17
Exercise 0: Solution
:client
plan
<<create>> :travelAgent
setItinerary
calculateRoute
18 18
Exercise 1
A traffic police uses a traffic violation app to find the
details of any traffic violation by entering the
violation id. Details of the interactions are the
following:
The police first presses the view button in the
Violation dialog box of the app.
This request is conveyed to the server object
The server object asks for the violation id
Once the police enters the violation id, the server
queries the DBproxy object using the id
Based on the response received from the DBProxy, the
server creates a violation object and passes it to the dialog
19
box for display.
Exercise 1: Solution
:Violations :Violations :Violations
Dialog server DBProxy
Police
view
view
id=getID()
getViolation(id)
<<create>> v:Traffic
May be a Violation
pseudo-
method
v DB is
display(v) queried
and the
result is
returned
as an
20
object 20
Method Population in Classes
Which methods should a class have?
Methods of a class are determined from the
interaction diagrams…
:Registration :Registratio
form n manager
RegistrationManager
add course
(joe, math 01)
addCourse(Student,Course
21
Example Sequence Diagram: Borrow Book
Use Case
borrow(book)
ok = canBorrow()
[ok] borrow(member)
setTaken(member)
22
23
Sequence Diagram: Frames
A frame consists of:
1) Diagram identifier
2) Participants in a
order
rectangle depicting process
the participating
objects: :client :order :inventory
A dotted line that
updat
extends for the time
e Locate item
period of the
interaction
3) Messages to
communicate among
the participants
24
Depicting a Frame Graphically
sd sample
update
operator op1
Interacti
on
Frame
Operatio Interaction
n Frame
Name: Operand
(e.g.
loop) Locate item
25
Combined Fragment: Syntax
op [guard_1]
interaction_1
…
[guard_n]
interaction_n
Divided into a set of interactions by dotted
lines
interaction_i is executed if guard_i is true
26
Frame Operators
Frame Meaning
Operato
r
Alt Alternative fragment for conditional logic
expressed in the guards
Loop Loop fragment while guard is true. Can
also write loop(n) to indicate looping n
times.
Opt Optional fragment that executes if guard
is true
Par Parallel fragments that execute in parallel
Regio Critical region within which only one
thread can run
n
27
Fragment Operators: Full List
ip
Conditional: operator “opt”
Sk
Loop: operator “loop”
Branching: operator “alt”
Reference: operator “ref”
Parallel: operator “par”
Critical Region: operator “critical”
Interrupt: operator “break”
Assertion: operator ‘’assert’’ 28
Example Sequence Diagram
order
:StoreFront :Cart :Inventor
y
loop
AddItem
ReserveItem
Need not
show: Implicit
Checkout Return
ConfirmOrde ProcessOrd
r er
PlaceItemInOrde
r
29
Sequence Diagram for Telephone Order
use case
Repeat
Everything in
the rectangle
30
Alternative Fragment
sd sample
Combined
Interaction client order inventory Interaction
Fragment Fragment
Operation
Name:
(Alternativ
e) Alt [new_cust=yes
]
cr_custinfo
()
Cr_order( )
Interaction
Fragment31
Operands
Example 2
32
Loop Fragment : Example
Searc :SearchEngi
h :Repository
ne
loo [hasNext
]
p getNext(
)
test(item)
brea [foun
k d] process(ite
m)
33
Linking Sequence Diagrams
If one sequence diagram is too large or refers to
another diagram, indicate it with either:
an unfinished arrow and comment
a "ref" frame that names the other diagram
Approved?
34
Nesting of Frames
:Foo :Bar
m1
opt [colour = red]
Loop [n<100]
calcula
te
distribut
e
35
Exercise 2: Print Server
A print server is an active object
Client applications send jobs to the print
server
The print server enqueues the received
object by calling a queue object
The job server takes up jobs one by one
from the queue:
Prints them by sending them to the printer
proxy
36
Exercise 2: Solution
Printing
A
Docume
nt
Activ :Printer
e :PrintServer :Queue Proxy
Client objec
Application t
print(doc,client) enqueue(job)
loop [queue-not-empty]
job=dequeue()
print(job)
status
done(status)
37 37
Code Generation
:Employee :EmployeeD
B
Emp=getEmployee(empId)
:ShapeFacto
ry
makeSquare
<<create
>> :Squar
e
:TreeMap :TreeNode
clear
<<destroy
>>
42
43
Sequence Diagram : Enroll Student
Write Java
u:URSDatabase Code for stu:Student
AssgSubCmd
procCmd(cmd)
parseCommand(cmd)
<<create>> a:AssgSubCmd
execute()
getStudent(id)
return stu
getSubject(subId)
[if stu != NULL and sub !
return sub = NULL]
addSubject(sub)
44
class AssgSubCmd{ Ans: Java
Code
private URSDatabase u;
Exercise 6
public execute(){
Student stu = u.getStudent(id);
Subject sub =
u.getSubject(subId);
if (stu != null && sub != null){
stu.addSubject(sub);
}
} 45
Exercise 7: Java Code for Sequence Diagram
:ShoppingBas
:Account :Order
ket
alt [ValidUser]
ref
placeOrder(Order: iOrderNo)
return()
return()
46
public void newTransaction(){
// behavior is an Interaction
if (ValidUser) // Alt combined fragment
{
placeOrder(iOrdNo); //Interaction
Occurrence
}
else
{
return;
}
} 47
Quiz: Write Code for class Y
48
Quiz: Ans
public class Y {
boolean doB(X x) {
Y y2 = new Y();
x.doD(y2);
return flag;
}
void doE() {---}
}
49
Exercise 8: Draw Sequence
Diagram
“Compute Price” use case is invoked by
customer in the context of a specific order
to calculate price of the order.
51
Exercise 8: Example Answer
getProduct
getPricingDet
ails
getDiscountInf
o
calculateDisco
unts
52
HW: Sequence diagram
Use Case: Add Calendar Appointment:
Scenario begins when the user chooses to add a
new appointment in the UI.
The UI notices which part of the calendar is active and
pops up an Add Appointment window for that date and
time.
The user enters the necessary information about
appointment name, location, start and end times.
The Appointment window would prevent the user from
entering an appointment that has invalid information,
such as an empty name or negative duration.
The calendar will record the new appointment in the
user's list of appointments.
53
53
HW cont…
Use Case: Add Calendar Appointment:
Alternate scenario:
If the user has an appointment at that time, the user
is shown a warning message and asked to choose an
available time or replace the previous appointment.
If the user enters an appointment with the same name
and duration as an existing group meeting, the
calendar asks the user whether he/she intended to join
that group meeting instead. If so, the user is added to
that group meeting's list of participants.
54
54
Collaboration Diagram
Known as Communication Diagram in UML
2
Shows both structural and behavioural
aspects:
Objects are collaborator, shown as boxes
3 : notify()
4 : update() s1 :StockQuote
Subscriber
1 : attach(s1)
Messages between objects p : Stock
6 : getState()
QuotePublisher 5 : update()
attach(s1)
attach(s2) Procedure call, RMI, JDBC, …
Observer
Time notify() design
pattern
update()
{update < 1 minutes}
getState()
update()
getState()
3 : notify() 4 : update()
s1 :StockQuoteSubscribe
1 : attach(s1)
6 : getState()
p : StockQuotePublisher 5 : update()
2 : attach(s2) s2 :StockQuoteSubscribe
56 56
7 : getState()
Collaboration Diagram for the renew book use
case
:Book
6: * find
9: update :Library
:Library
Book
:Library
:Library
Boundary Renewal
Book :Book Member
Register
Controller
:Library
Book renewBook
[reserved] Register
find MemberBorrowing
displayBorrowing
selectBooks
bookSelected
8: apology 10:
5: book * find
confirm [reserved]
Selected
[reserved] apology
1: [reserved] update
:Library apology
2: findMemberBorrowing 57
updateMemberBorrowing
4: selectBooks
12: confirm
:Library
updateMemberBorrowing
Member
57
Object-Oriented
Analysis and
Design
58
OOAD
OOA OOD/OOP
Domai
Specification Definition n Construction
of Model of Progra
the problem Use the solution m
case
model
59
OOA versus OOD?
Analysis:
An elaboration of requirements.
Independent of any specific
implementation
Design:
A refinement of the analysis model.
Takes implementation constraints into
account
60
Design Process
OOA OOD
User interface
Issues or GUI
Use case Interaction
prototype diagram diagram
Start
Glossary
61
Domain Modelling
Represent objects appearing in the
problem domain.
Also capture object relationships.
Three types of objects are identified:
Boundary objects
Entity objects
Controller objects
62
Boundary Objects
Handle interaction with actors:
User interface objects
Often implemented as screens, menus,
forms, dialogs etc.
These do not perform any processing:
But may only validate input, format
output, etc.
63
Entity Objects
Hold information over long term:
e.g. Book, BookRegister, Member
Normally are dumb servers:
Responsible for storing data, fetching
data etc.
Elementary operations on data such as
searching, sorting, etc.
Often appear as nouns in the problem
64
description...
Controller Objects
Help to realize use case behavior:
Interface with the boundary objects
Coordinate the activities of a set of entity
objects
Embody most of the business logic:
Take overall responsibility for use case
execution.
Usually a use case is realized by one
controller.
65
Controller Classes
Controller classes coordinate,
sequence, transact, and otherwise
control other objects… Controll
er
Name controller attributed to
Smalltalk MVC mechanism:
Where such objects were
called controllers…
Boundar Entity
y
66
Example Use Case Realization
register
Customer customer Clerk
Manager Supermarket
Prize scheme
68
Identification of Controller Objects
Examine the use case diagram:
Add one controller class for each use case.
Later on, some controllers may be removed or may
need to be split into two or more controller classes
if they have too much responsibility.
register
Customer customer Clerk
register
Play Move sales
Sales Clerk
select
Tic-tac-toe game
Player winners
Supermarket
Manager Prize scheme
69
Identification of Entity Objects
Usually appear as common nouns in the
problem description.
From the list of nouns, need to exclude:
Users (e.g. accountant, librarian, etc)
Passive verbs (e.g. Acknowledgment)
Those with which you can not associate any methods
Those with which you can not associate any data to
store
Surrogate users may exist as classes:
Library member
70
Identify Classes
A partial requirement:
The user must be allowed to specify each product by
its primary characteristics, including its name and
product number. If the bar code does not match the
product, then an error should be generated to the
message window and entered into the error log. The
summary report of all transactions must be structured
as specified in section 7.A.
Of course, not all nouns will correspond to a
class or object in the final solution
71
Identify Entity Classes
Eliminate improbable nouns:
The user must be allowed to specify each product by
its primary characteristics, including its name and
product number. If the bar code does not match the
product, then an error should be generated to the
message window and entered into the error log. The
summary report of all transactions must be structured
as specified in section 7.A.
73
Identify Classes by Noun Analysis
A partial requirements document:
74
It is Challenging to Identify Classes!
Example:
The aggregator
corresponds to registers in *
CustomerRecor
physical world d
76
Naming Classes
Class names should be singular nouns
Examples: Member, Student, Book
77