UML Basics: Paolo Ciancarini
UML Basics: Paolo Ciancarini
Paolo Ciancarini
The soul
never thinks
without an image
Aristotle, De Anima
Agenda
• Use case
• Class (Object diagrams are class diagrams without classes )
• Behavior
– Statecharts
– Activity
– Interaction
• Sequence
• Collaboration
• Implementation
– Components
– Deployment
Canonical diagrams (Superstructure, vers. 2.4)
Hierarchy
Lattice
Organizational
structures
Modules vs components
Discuss
• Which ways do you know to pictorially
describe “behaviors” - or actions?
Flowchart
Assembly
instructions
Napoleon in Russia
(Minard 1869)
Exercise:
structural or behavioral?
Static Dynamic
Class diagram State diagram
(Object diagram) Collaboration diagram
Component diagram (Sequence diagram)
(Deployment diagram) (Activity diagram)
Example
• A chess program could be “stand-alone”,
“client-server”, “agent based”, etc.
• Its behavior should always be coherent
with the rules of chess
• What is its goal? To play and win a chess
game against an opponent
Goals and responsibilities
• The very same chess program, with identical structure
and behavior, could be used with a different goal?
• For instance, could it be used to learn to play chess?
Responsibility of the program: teach chess
• Or to write a chess book, like a chess game editor?
Responsibility of the program: write chess texts
• Or to play a game of loser’s chess (where who is
checkmated wins)? Responsibility: play games with rules
slightly different from chess
<<extend>>
Play Play with other rules
Teach
User
Write
Use Case diagram
Negotiate policy
Sales staistics
use case
actor Register
Student
Check
Grades
<<include>>
Validate User
Elements of a Use Case Diagram
• Actor:
– Represents a role played by external entities
(humans, systems) that interact with the system
• Use case:
– Describes what the system does (i.e., functionality)
– Scenario: sequence of interactions between the
actors and the system
• Relationships:
– Association between actors and use cases
– Extension (or generalization) among actors
– Dependency among use cases: include and extend
Example
Register
User User
<<include>>
Check Grades
Validate User
Student
Student Faculty Get Roster
<<include>>
<<extend>>
Faculty
Enter Grades
Use Case Scenario
Use Case: Check Grades
Description: View the grades of a specific year and semester
Actors: Student
Precondition: The student is already registered
Main scenario:
User System
1. The system carries out “Validate User”, e.g.,
for user “miner” with password “allAs”.
2. The system prompts for the year and semester.
3. The user enters the year and
semester, e.g., Fall 2013.
4. The system displays the grades of the courses
taken in the given semester, i.e., Fall 2013.
Alternative:
The student enters “All” for the year and semester, and the system displays
grades of all courses taken so far.
Exceptional:
The “Validate User” use case fails; the system repeats the validation use case.
<<extend>> vs
<<include>>
• A use case B is included in
use cases C and D when
these have some common
steps represented by B
• A use case B extends a
use case C when B applies
optionally, under some
condition (usually specified
in the scenario)
Conceptual/computational world
Real world
Abstraction
Interpretation
Data-oriented Object-oriented
Key Ideas of OO Modeling
• Abstraction
– hide minor details so to focus on major details
• Encapsulation
– Modularity: principle of separation of functional concerns
– Information-hiding: principle of separation of design decisions
• Relationships
– Association: relationship between objects or classes
– Inheritance: relationship between classes, useful to represent
generalizations or specializations of objects
• Object-oriented language model
= object (class) + inheritance + message send
The basic building blocks of UML
Water
Fresh water
have
Rivers
Oceans
have
have have
live in Salt water
Fish have
Crocodiles
Penguins
class 1
getCreditRating(): String operation
{if
[Link] generalization
is “poor” then [Link]
must be true}
lineItems * {ordered}
constraint
Order line
quantity: Integer Corporate Customer
price: Money contactName
creditRating Personal Customer
* creditLimit
multiplicity creditCardNumber
*
{getCreditRating()==“poor”}
role name salesRep 0..1
1
Product Employee
Notation for classes
• The notation for classes is a rectangular box with
three compartments
Point
x
Point
y
Move
Point
- x: int
- y: int
+ move(dx: int, dy: int): void
Example
A document defined by classes at three different abstraction levels
Document
Document Pages[]
nPages
display
Document
- Pages: array of Page
- nPages: int
+ display(k:int, p:Page): void
Exercise
Draw a class diagram for the following Java code
class Person {!
private String name;!
private Date birthday;!
public String getName() {!
// …!
}!
public Date getBirthday() {!
// …!
} !
}!
A counter class
Counter class Counter{!
private counter: integer;!
- counter: integer public integer display()!
{return counter};!
public void tic()!
+ display: integer {counter = counter + 1};!
+ tic: void public void reset()!
+ reset: void
{counter = 0};!
A class in UML }!
A corresponding class
in a programming language
c3:Counter p:Printer
x = 10 x = 30 x = 20
y = 20 y = 30 y = 30
p1: Point
homepage: X=0 Y=0
Document
mythesis:
Document p3: Point
X=1 Y=0
Example (object diagram)
r:Robot
[moving]
w:World
a1:Area a2:Area
Element
C <<covalent>>
Carbon Hydrogen
C H
C
<<covalent>>
59
Example: molecule
(object diagram)
:Hydrogen :Hydrogen
:Hydrogen :Hydrogen
60
Objects vs. Classes
Interpretation in the Representation in the
real world model
Object An object is anything in the An object has an identity, a
real world that can be state, and a behavior
distinctly identified
:John :SwArch
Association and roles
• The simplest relationship among classes is the
association
• An association represents a structural relationship that
connects two classes
• It means that the two classes “know” each other: all
objects in a class have some relationship with some
object(s) in the other class
• An association can have a name, which usually
describes its role
Class diagrams denote systems of objects
from
Flight City
to
from to
Roma:City AZ611:Flight Boston:City
Association with direction
• An association may have an optional label
consisting of a name and a direction arrow
• The direction arrow indicates the direction of
association with respect to the name
enroll
Student Course
0..* 1
Student Faculty
advisee advisor
Association example
• A Student can take up to five Courses
• Every Student has to be enrolled in at least one course
• Up to 300 students can enroll in a course
• A class should have at least 10 students
takes
Student Course
10..300 1..5
Association Example
- Multiplicity
• A teacher teaches 1 to 3 courses
• Each course is taught by only one teacher
• A student can take between 1 to 5 courses
• A course can have 10 to 300 students
1 teaches 1..3
Teacher Course
1..5
takes
Students
10..300
Exercise
Explain the meaning of this diagram
1
1
Teacher
advisor
Bank Exercise
accountNumber:Integer
0..1
customer
Person Company
manager 0..*
isMarried : Boolean name: String
managedCompanies
isUnemployed : Boolean numberOfEmployees: Integer
birthDate : Date
employee employer
age : Integer 0..* 0..*
stockPrice() : Real
firstName : String
lastName : String
sex : Sex wife
0..1
income(Date) : Integer
husband 0..1
Job
title : String
startDate: Date
Marriage salary: Integer
place: String
date: Date
Net data structures
• How we can represent a net of objects from the
same class?
• A class with an association to itself with both
ends of the association marked with 0..*
a1:A
A 0..*
a1:A
A 0..*
*
Element
1
Directory File
Non-hierarchic file system
• A directory can contain any number of
elements (either a file or a directory)
• An element can be part of many directories
*
Element
Directory File
Aggregation
• An aggregation is a special form of association
representing has-a or part-whole relationship
• It distinguishes the whole (aggregate class) from its parts
(component class)
• WARNING: an aggregation does not bind the parts’ lifetime
to the whole (they can exist separately)
Whole Part
Course Students
Example of an aggregation hierarchy
Computer Science
Degree
Whole Part
Apartment Room
Example of a composition hierarchy
MicrowaveOven
University
1..*
1 1..* 1 0..*
College Department Student
1 1
chair-of member-of
1 1..*
Faculty
Example
sub-team
0..*
0..* 1..*
0..1 Team Employee
1
builds
1..*
1 1..* 0..*
Airplan Component sub-assembly
0..*
assembly
Aggregation vs composition
homePhone
Person PhoneNumber Aggregation:
A Person uses two phone numbers;
workPhone CountryCode Numbers are independent from
Prefix
Number
Persons
homePhone
Person PhoneNumber
Composition:
workPhone CountryCode A Person has two phone numbers;
Prefix Numbers are dependent from
Number Persons
Aggregation vs composition
Windsurf use
0..1 1
Aggregation:
Sail Windsurfs and boats use sails.
The same sail can be used
Boat use
in a Windsurf or in a Boat
0..1 1
Windsurf has
Composition:
0..1 1
Sail Here windsurfs and
boats have each their
Boat has own sails which are
0..1 1
destroyed when the
“container” is
destroyed
Exercise
aggregation or composition ?
– Building and rooms
– Course and lessons
– TV channel and programs
– Parliament and members
– Sky and stars
– Country and cities
– City and buildings
– Wood and trees
Example
Exercise
Imagine some aggregation or composition
relationships among the following classes
and draw a corresponding class diagram
– Employee
– Manager
– Office
– Department
Dependency
• A dependency of A from B is a relationship
between two entities A and B such that the proper
operation of A depends on the presence of B, and
changes in latter would affect the former
• Example: a common form of dependency is the
use relation among classes
<<use>>
Class1 Class2
<<use>>
Program Compiler
Example: dependencies in a class diagram
Registrar CourseSchedule
Student
Collaboration
Use case <<Implements>>
<<Implements>>
<<Implements>>
Class A
Class B
Use case description:
1. Actor pushes button Class C
2. Use case does something
3. Use case responds with Op1()
message Op2() Op1()
4. ... Op2() Op1()
Op2()
Class and superclass
Point
x
y
Point Move
…
color
…
SetColor
Example
1 1..* call
Phonebill Phonecall 0..* 1 Phone
Origin {complete,disjoint}
Mobileorigin
call from
Mobilecall Cellphone Fixedphone
0..* 0..*
Inheritance
• Key relationship in object modeling
• Inheritance defines a relationship “IS_A” among
classes or interfaces
• In UML there are three kinds of inheritance
– extension relation between two classes (subclass and
superclass)
– extension relation between two interfaces
(subinterface and superinterface)
– implementation relation between a class and an
interface
Three kinds of inheritance
• An extension relation is called specialization and
generalization
• An implementation relation is called realization
add(object o)
get(int index)
Interfaces in Java
<<interface>>
interface Drawable {
Drawable
void draw(Graphics g);
+ draw(g: Graphics): void
}
Interfaces
• A class and an interface
<<interface>>
differ: a class can have Person
an actual instance of its firstName: String
type (but it can also lastName: String
Student
{abstract}
Graduate
No-degree Undergraduate
{abstract}
Master PhD
Example
Student
{abstract}
Graduate
No-degree Undergraduate
{abstract}
Master
PhD
Exercise
[Link]
Real
example:
LinkedIn
Real example: Facebook
Real example: DOM
Strange examples
A 1 1
A
1 1
A A
Behavior
diagrams
DYNAMICS
OBJETC’S
states and transitions (finite state machines)
• Activity diagram
– Describes the control flow among objects by
actions organized in workflows (Petri Nets)
• Sequence diagram
INTERACTION
– Depicts objects’ interaction by highlighting the
OBJETCS’
time ordering of method invocations
• Communication (collaboration) diagram
– Depicts the message flows among objects
Behavioral elements
q Verbs in the requirements
q Dynamic parts of UML models: “behavior over time”
q Usually connected to structural elements
q Interaction
a set of objects exchanging messages, to accomplish a specific purpose.
harry: Student
ask-for-an-A paul: Professor
name = “Harry White” name = “Paul Smith”
q State Machine
specifies the sequence of states an object goes through during its lifetime in
response to events
received-an-A/buy-beer
inStudy inParty
sober/turn-on-PC
State diagram: booking object
State diagram
• A state diagram represents the behavior of an object
• Graph: net of states (nodes) and transitions (arrows)
• Graph representing a finite state machine
• Useful for modeling a reactive (event-driven) system
• Animation by “token game”
push switch
Off On
push switch
State diagram: elements
Transition
Idle Running
State
Example: Unix process
end
fork Pre-empted
Running
Ready scheduled
Sys call
Sys return
Waiting
State
• Situation in the life of an object (or system)
during which it:
– Satisfies some condition,
– Performs some activity, or
– Waits for some events
• Set of values of properties that affect the
behavior of the object (or system)
– Determines the response to an event,
– Thus, different states may produce different
responses to the same event
State in a state diagram
• States are rounded rectangles with at least one section
– Mandatory field: name
• optional: list of internal actions (with optional guards)
– format: event-name argument-list | [ guard condition ] / action-expression
– special actions: 'entry/' and 'exit/' (these cannot have arguments or guards)
• optional: invoking a nested state machine
– format: do/machine-name
– 'machine-name’ must have initial and final states
Enter Password
reset
tic
Transition
• Relationship between two states indicating that a
system (or object) in the first state will:
– Perform certain actions and
– Enter the second state when a specified event occurs
or a specified condition is satisfied
• A transition consists of:
– Source and target states
– Optional event, guard condition, and action
dial digit(n)
[incomplete]
connected Ringing
Dialing Connecting
dial digit(n)
[valid] / connect
dial digit(n)
[invalid] busy
Busy
Invalid
Example
recovery success
recovery failure
anomaly Recovery
Normal
Identification
temperature
pressure
recovery
failure
recovery
Pressure Temperature
success Recovery Recovery
recovery
failure
recovery success
Composite states
Recovery
anomaly
Normal Recovery
Identification
recovery
success
pressure temperature
Pressure Temperature
recovery Recovery Recovery
failure
Composites and transitions
Active
Idle
Validating
Selecting Processing
Maintenance
Printing
Dial Number
Include / Dialing
Dialing
[[Link]()]
digit(n)
Composite state
• Used to simplify diagrams
• Inside, it looks like a statechart
• It may have composite transitions
• It may have transitions from substates
• It can be sequential or parallel
Example
do / add assets
cancel
Cancelled Complete
Exploiting
a
composite
state
Parallel composition
• Concurrency (multiple threads of control)
• Synchronization
Superstate
substate1 substate2
substate3 substate4
Example
Incomplete
Mod1 Mod2
Project Passed
fail
Midterm Final Failed
Protocol state machine
• Normally we use a state diagram to show the internal
behavior of all objects of a class
• Sometimes, however, we want to show a complex
protocol (set of rules governing communication) when
using an interface for a class
• For example, when we access a database we need to
use operations like open, close and query. But these
operations must be called in the right order: we cannot
query the database before we open it
Protocol state
machine
<<boundary>>
DatabaseAccessor
-dbname
-password
-comArea
-queryStatement
DBaccess
+open()
+close()
+query()
+fetch()
+cancel()
+create()
+kill()
Behavioral vs protocol state machine
new enrollment to
a different course
Student
change role
end studying
studies
change career
Graduate Sportsman
Exercise: Cellular Phone
initial
Add student
A diagram whose nodes
fork/spawn
represent activities,
while arrows represent the
Notify Registrar Notify Billing order the activities happen
synchronization
decision [else]
[ count < 10 ]
guard
Close course final
Example
[incorrect]
Fill out Obtain help
enrollment forms to fill out forms
[correct]
Enroll in
university
Attend university
[accepted] overview presentation
[rejected]
Enroll in seminars Make initial
tuition payment
Example
Receive order
Close order
Activity diagram
Example: hotel reservation
Activity control nodes
• Initial node • Merge node
• Decision node • Activity final node
• Fork node • Flow final node
• Join node
Activity partition
• Partitions divide the diagram to constrain and show some special view
• Partitions often correspond to organizational units in a business model
Swimlanes
in an
activity diagram
showing a
workflow
with several roles
Exercise Which is the maximum degree of
parallelism in this activity diagram?
What an AD does not show?
• Objects (but they can be inferred)
• States
• Messages
• Data passed between steps
• User interface
How to create an AD
1. Identify the activities (steps) of a process
2. Identify who/what performs activities (process steps)
3. Identify decision points (if-then)
4. Determine if a step is in loop
5. Determine if a step is parallel with some other
6. Identify the order of activities, decision points
Example
Step Process Step Who/What Parallel Loop Preceding
ID or Decision Performs Activity Step
5
3
4 6
Example
8
10
State vs activity diagrams
• Both diagrams describe behaviors, by state
changes and actions, respectively
• In UML1 they are equivalent (in AD states are
actions)
• In UML2 they differ: ActivityD are based on Petri
Nets, StateD on Harel automata
• Their typical usage is also different:
– State diagrams are single context
– Activity diagrams are multiple context
State machine: chess game
Black wins
White’s move
start stalemate
black white
Draw
moves moves
stalemate
Black’s move
White wins
Activity diagram: chess game
White
move move
move move
Black
State vs activity diagrams
Pe2e4 Ng1f3
Pe7e5 Nb8c6
Black
State vs activity diagrams
Activity diagram vs flowchart
• An activity diagram shows the order in
which to do tasks
• The key difference between an activity
diagram and a flowchart is that the activity
diagram can describe parallel processes,
while flowcharts are sequential
Behavior
diagrams:
interaction
Balla: Dinamismo di cane al guinzaglio, 1912
Modeling Interaction
• Statechart diagram
– Depicts the flow of control inside an object using
states and transitions (finite state machines)
• Activity diagram
– Describes the control flow among objects by
actions organized in workflows (Petri Nets)
• Sequence diagram
INTERACTION
– Depicts objects’ interaction by highlighting the
time ordering of method invocations
• Communication (collaboration) diagram
– Depicts the message flows among objects
Interaction diagrams
• A use case diagram presents an outside view of
the system
• The inside view of a system is shown by
interaction diagrams
object
lifetime
activation message
bar
Sequence diagram
Messages between objects
• message (method call) indicated by an
horizontal arrow to another object
– write the message name and arguments above arrow
Activation
:Controller
Nesting
Sequence diagram: flow
place an order
process
validate
Sequence of message transmissions
if ( payment ok )
if ( not in stock )
deliver
back order
get address
mail to address
Linking sequence diagrams
• if a sequence diagram is too large or refers to
another diagram, indicate it with either:
– an unfinished arrow and a comment
– a ref frame that names the other diagram
Approved?
Conditionals and loops
• frame: box around part of a sequence diagram to
indicate selection or loop
– if : (opt) [condition]!
– if-else: (alt)[condition] else [condition]
– loop: (loop)[condition to loop over]!
[Link]
Example
Example
Using a SD for workflow
A real
example
(from
[Link])
Consistency among diagrams
We can derive the dependencies shown in a class diagram
from the interactions defined in a sequence diagram
buys valid for
Transaction Ticket Zone
insertChange()
updateBalance()
ack
<<create>> :Ticket
printedTicket
Exercise
Draw a sequence diagram showing how a
customer interacts with a travel agency, a station
and a train to reach some destination
link
1.2 [ok] : deliver(c)
1 : place an order(c)
c : Customer 1.2.2 : get address() p : Product
: Supplier
Communication diagram
Collaboration 1.1 : ok := validate() : Payment
: Order
1 : place an order(c)
c : Customer 1.2.2 : get address() p : Product
: Supplier
Example
SD vs CD
Use Case
Class diagram
Sequence diagram
• On class diagrams
[Link]/developerworks/rational/library/content/
RationalEdge/sep04/bell/[Link]!
• On activity diagrams
[Link]/developerworks/rational/library/[Link]!
• On sequence diagrams
[Link]/developerworks/rational/library/[Link]!
!
UML Specification Documents
• OMG, UML Specification version 1.5, 2003
• OMG, UML Superstructure version 2.4.1, 2011
• Rumbaugh, Jacobson, Booch, The UML Reference
Manual, Addison Wesley, 1999 and 2004 (2nd ed)
References on using UML
• Booch, Rumbaugh, Jacobson, The UML User Guide,
Addison Wesley, 1998 and 2005 (2ed)
• Fowler, UML Distilled, 3ed, Addison Wesley, 2003
• Pilone and Pitman, UML 2.0 in a Nutshell, OReilly, 2005
• Ambler, The Elements of UML 2.0 Style, Cambridge
University Press, 2005"
Useful sites
• [Link] Documents defining the standard!
• [Link]!
• [Link]/!
• [Link]/essays/[Link]!
• [Link]/uml/[Link]!
• [Link]/software/awdtools/rmc/library!
• [Link]/en-us/library/[Link]!
• [Link]/courses/cs211/ATMExample!
• [Link]!
• [Link]/uml/!
• [Link]/ITMUML/[Link] Online courseware
• [Link]/modeling/mdt/uml2/docs/articles/Getting_Started_with_UML2/[Link]
Tools
• Eclipse + several plugins, like Omondo
• [Link] Argo or Poseidon
• [Link] free online tool, sharable diagrams
• [Link] web application, need license!
• [Link] Open source editor for UML!
• [Link]/us/products/together/[Link] Borland Together
• [Link] Visual Paradigm suite!
• [Link] Magicdraw suite!
• [Link] text UML!
• [Link] web application for class and seq diagrams!
• [Link]/software/rational/ Rational Rose
• [Link] IBM platform
• [Link] UML on tablet PC!
• [Link] Beautiful UML diagrams in LaTeX
• [Link]/uml Images reusable in a graphic editor!
• [Link] Fast draw of UML diagrams for web pages!
UML blogs and fan clubs
• [Link]/groups/UML-Lovers-143183/about
• [Link]/uml-and-sysml/
• [Link]/about-geert-bellekens/
Questions?