0% found this document useful (0 votes)
35 views77 pages

Lect 13

The document provides an overview of sequence diagrams and their components, including messages, activation, and object lifetimes. It includes examples of sequence diagrams for various use cases, such as library book renewal and traffic violation queries. Additionally, it discusses asynchronous messages, return values, and the syntax of combined fragments in UML sequence diagrams.

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)
35 views77 pages

Lect 13

The document provides an overview of sequence diagrams and their components, including messages, activation, and object lifetimes. It includes examples of sequence diagrams for various use cases, such as library book renewal and traffic violation queries. Additionally, it discusses asynchronous messages, return values, and the syntax of combined fragments in UML sequence diagrams.

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/ 77

Sequence Diagram

and OOAD
Lecture 13

11-03-2025

1
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
2
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

3
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

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)

 A return of control from the synchronous


message
 A creation of a new entity 5
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. 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

Procedure call or other kind of


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

Asynchronous flow of control(The


sender does not expect a reply)

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

[any key press]


<<destroy>>

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

member: book:Book :Book


LibraryMember Copy

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

:client :order :inventory


Interaction
Frame

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
()

Interaction [new_cust= no]


Fragment
guards
get_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

Customer Info ref

Verify customer credit

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)

Public class EmployeeDB{


public Employee getEmployee(String empId)
{

} 38
Write Java Code for ShapeFactory Class…

:ShapeFacto
ry
makeSquare
<<create
>> :Squar
e

Public class ShapeFactory{


public Shape makeSquare(){
return new Square(); }
} 39
Exercise 3

:TreeMap :TreeNode
clear
<<destroy
>>

Public class TreeMap{


private TreeNode t;
Write public void clear(){
Java
t=null;
Code
}
}
40
PurchaseItem Use Case: Sequence
Diagram
:Controller
Write Java
purchase
Code for
<<create>
> :Purchase
Controller
public Class Controller {
buyGrocery

private Purchase myPurchase;


<<create(cashTender) :Payment
>>
private Payment myPayment;
public void purchase() {
myPurchase = new Purchase();
myPurchase.buyGrocery();
myPayment = new
Payment( cashTender );
}
41 41
// . .
<<Create>>

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.

 All the line items are examined to determine


their prices, which are based on the pricing
rules of the order line’s products.

 Then the overall discount is computed, which


is based on rules tied to the customer.
50
Solution : First Identify Classes

“Compute Price” use case is invoked by
customer in the context of a specific
order to calculate price of the order.

 All the line items are examined to determine


their prices, which are based on the pricing
rules of the order line’s products.

 Then the overall discount is computed, which


is based on rules tied to the customer.

51
Exercise 8: Example Answer

:Custome :Order :OrderLin :Product


r e
calculatePric
e
Loop For all line items
getQuantity

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()

shown as labelled arrow 2 : attach(s2) s2 :StockQuote


Subscriber
7 : getState()

placed near links



Messages are prefixed with sequence
55
numbers to show relative sequencing
Interaction Diagram: sequence vs
communication
objects

p : StockQuotePublisher s1 : StockQuoteSubscriber s2 : StockQuoteSubscriber

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

:Library renewBook Book 7: apology


confir
Boundary 3: display Renewal m

Borrowing Controller confirm

2: findMemberBorrowing 57
updateMemberBorrowing

4: selectBooks

12: confirm
:Library
updateMemberBorrowing
Member

57
Object-Oriented
Analysis and
Design

58
OOAD

An Iterative and Incremental process.

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

SRS Domain Class


document model diagram
Code

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

Boundary 1 Controller Boundary 2

Entity 1 Entity 2 Entity 3

• A use case is realized through the collaboration of


a controller and several boundary and entity objects
67
Identification of Boundary Objects

Need one boundary object :
 For every actor-use case pair

register
Customer customer Clerk

Play Move register


sales
Sales Clerk
Tic-tac-toe game select
Player winners

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.

Improbable nouns: Nouns with which no attributes


or methods can be associated
72
Noun Analysis: Another
Example

A trading house maintains names and addresses of its


regular customers. Each customer is assigned a unique
customer identification number (CIN). As per current
practice, when a customer places order, the accounts
department first checks the credit-worthiness of the
customer.

73
Identify Classes by Noun Analysis


A partial requirements document:

A trading house maintains names and addresses of its


regular customers. Each customer is assigned a
unique customer identification number (CIN). As per
current practice, when a customer places order, The
accounts department first checks the credit-worthiness

Not all nouns correspond to a class in the domain
of the customer.
model

74
It is Challenging to Identify Classes!

Often it is challenging to decide:


Whether something should be represented as a


class

Example:

Should an employee's address be represented as


a set of instance variables or as an Address object

When a class becomes too complex,:


Itshould be decomposed into multiple smaller


classes to distribute the responsibilities 75
Identification of Entity
Objects: Some Hints

Usually:
 Appear as data stores in
DFD CustomerRegis
ter
 Occur as aggregate objects

 The aggregator
corresponds to registers in *
CustomerRecor
physical world d

76
Naming Classes


Class names should be singular nouns
 Examples: Member, Student, Book

Book Member Student

77

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy