UML Basics: Lecturer: Valentina Presutti Academic Year: 2009/2010 Courtesy of Paolo Ciancarini
UML Basics: Lecturer: Valentina Presutti Academic Year: 2009/2010 Courtesy of Paolo Ciancarini
Corso di Laurea Magistrale in Ingegneria Informa4ca
Aristotle, De Anima
Agenda
• Modeling notations
• UML 1.* and UML 2.*
• Models and Views
• Basic diagrams
• Structures, behaviors, interactions
• Case study
Modeling - a foundation of all engineering disciplines
Models
improve
communica4on
and
understanding
about:
• why
the
system
is
needed;
Requirements
• what
its
func4onality
should
be;
Functional • how
it
should
be
implemented
requirements
Non-functional Design
requirements Functional
design
Expresses needs
Implementation
design Implementation
hardware
software
Fulfils needs
User Owner
A
modeling
engineering
spiral
has needs
Model Domain
Domain
models
Deploy Develop
Manufacture System
System
models
quality =
satisfaction of needs
Visual
documenta4on
Fulfill Order
• Use case
• Class (Object diagrams are class diagrams without classes )
• Behavior
– Statecharts
– Activity
– Interaction
• Sequence
• Collaboration
• Implementation
– Components
– Deployment
Canonical
diagrams
(Superstructure,
vers.
2.0)
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 Scenarios
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 2007.
4. The system displays the grades of the courses
taken in the given semester, i.e., Fall 2007.
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.
Exercise
• Draw a use case diagram and a related
scenario for the following situation:
Conceptual/computational world
Real world
Abstraction
Interpretation
Data-oriented Object-oriented
Key Ideas of OO Modeling
• Abstraction
– Mechanisms to 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
UML 1.x
Structural — nouns/static of UML models (irrespective of time)
Main
Behavioral — verbs/dynamic parts of UML models.
Student Person
2. Generalization
a specialized element (the child) is more specific than the generalized element
Jonh:Student <<instanceOf>>
Student
4. Dependency
a change to one thing (independent) may affect the semantics of the other thing (dependent)
(direction, label are optional)
Class
• Defines the structure of the states and the
behaviors shared by all the instances
• Defines a template for creating instances
– Names and types of all fields
– Names, signatures, and implementations of all
methods
Class diagram
• Most common diagram in OO modeling
• Describes the static structure of a system
• Consists of:
– Nodes representing classes
– Links representing of relationships among
classes
• Inheritance
• Association, including aggregation and
composition
• Dependency
Notation for classes
• The UML notation for classes is a rectangular
box with as many as three compartments
Point
x
Point
y
Move
Point
- x: int
- y: int
+ move(dx: int, dy: int): void
Example
Document
Pages[]
Document
nPages
display
Point
- Pages: array of Page
- nPages: int
+ display(k:int, p:Page): void
Field and Method Declarations
class Person {
private String name;
private Date birthday;
public String getName() {
// …
}
public Date getBirthday() {
// …
}
}
Objects vs. Classes
Interpretation in the Representation in the
Real World Model
Object An object represents An object has an identity, a
anything in the real world state, and a behavior.
that can be distinctly
identified.
x = 10 x = 30 x = 20
y = 20 y = 30 y = 30
Association
• General binary relationship between classes or
objects
• Represented as a line between boxes
Student Course
:John :SwEng
Association
• An association line may have an optional label
consisting of a name and a direction
• 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
Student Course
10..300 takes 1..5
54
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
55
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
0..*
A
a1:A
0..*
A
1
1
Teacher
advisor
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
Hierarchic file system
• A directory can contain any number of
elements (either a file or a directory)
• Any element is part of exactly one directory
*
Element
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
Composition
• A composition is a stronger form of aggregation
• It implies exclusive ownership of the component
class by the aggregate class
• The lifetime of the parts is entirely included in the
lifetime of the whole (a part can not exist without
its whole)
Whole Part
Apartment Room
Example
University
1..*
1 1..* 1 0..*
College Department Student
1 1
chair-of member-of
1 1..*
Faculty
Exercise
Imagine some possible aggregation or
composition relationships among the
following classes and draw a corresponding
class diagram
– Employee
– Manager
– Office
– Department
Dependency
• Relationship between the entities such that the
proper operation of one entity depends on the
presence of the other entity, and changes in one
entity would affect the other entity
• The common form of dependency is the use
relation among classes
<<use>>
Class1 Class2
<<use>>
Program Compiler
Example
Registrar CourseSchedule
x
y
Point Move
…
color
…
SetColor
Notation for Interfaces
<<interface>>
Drawable
interface Drawable {
void draw(Graphics g);
+ draw(g: Graphics): void
}
Interfaces
• A class and an interface
differ: a class can have
an actual instance of its
type (but can also have
zero instances),
whereas an interface
must have at least one
class to implement it
• Example: both the
Professor and Student
classes implement the
Person interface
Example
Student
{abstract}
Graduate
No-degree Undergraduate
{abstract}
Master PhD
Exercise
1 1
A A
1 1
A A
Behavior
diagrams
INTERACTION
ordering
of
method
invoca4ons
• Communica4on
(collabora4on)
diagram
– Depicts
the
message
flows
among
objects
Behavioral elements
Verbs in the requirements
Dynamic parts of UML models: “behavior over time”
Usually connected to structural elements
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”
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
• 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
Elements of a state diagram
StateName State1 State3
[condition]
event
transition
State2
do/action2
Superstate
Start Dial
digit(n)
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
Composite state
• Used to simplify diagrams
• Inside, looks like a statechart
• May have composite transitions
• May have transitions from substates
• Sequential and parallel
Composites and transitions
Active
Idle
Validating
Selecting Processing
Maintenance
Printing
Dial Number
Include / Dialing
Dialing
[number.isValid()]
digit(n)
Parallel composition
• Concurrency (multiple threads of control)
• Synchronization
Superstate
substate1 substate2
substate3 substate4
Example
Incomplete
Mod1 Mod2
Project Passed
fail
Midterm Final Failed
History pseudo state
• A history pseudostate represents the most recent active
substate of its containing state
• There are two kinds of this pseudostate: shallow or deep
(See the Superstructure sect 15.3.8 pag 541 for their definition)
Consistency
among diagrams Student
practices
enrolls * FirstName *
LastName
Age
Role 0..*
1
DegreeProgram Sport
Enrolls a differenr
program
Student
Changes role
Finishes education
program Studies
Changes carreer
Graduated Sporty
Exercise: Cellular Phone
• Draw a statechart describing the operation of a cellular
phone. Assume that the phone has keys for:
– power on and off
– keypad locking and unlocking
– 0-9, #, and *
– talk (or send) and end
Model the following operations:
– power on/off
– keypad locking/unlocking
– making calls (e.g., dialing, connecting, talking),
– receiving calls (e.g., ringing, talking)
Activity diagram: elements
A special kind of state diagram that shows the flow from activity to activity
initial
Add student
fork/spawn
synchronization
[else]
[ count < 10 ]
guard
Close course final
Example
Example
Example
Example:
business
plan
Activity partition
• Partitions divide the nodes and edges to constrain and show a view of the contained
nodes
• Partitions can share contents; they often correspond to organizational units in a
business model
Swimlanes
in an
activity diagram
showing a
workflow
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
• Also their typical usage is different: SD are
single context, AD multiple context
State vs activity diagrams
Pe2e4 Cg1f3
Pe7e5 Cb8c6
Black
Exercise
Which is the
maximum
degree of
parallelism in
this activity
diagram?
Behavior
diagrams:
interaction
Balla: Dynamism of a Dog on a Leash, 1912
Modeling Interaction
• Statechart
diagram
– Depicts
the
flow
of
control
inside
an
object
using
states
and
transi-ons
(finite
state
machines)
• Ac4vity
diagram
– Describes
the
control
flow
among
objects
by
ac4ons
organized
in
workflows
(Petri
Nets)
• Sequence
diagram
– Depicts
objects’
interac4on
by
highligh4ng
the
-me
INTERACTION
ordering
of
method
invoca4ons
• Communica4on
(collabora4on)
diagram
– Depicts
the
message
flows
among
objects
Interaction diagrams
• A use case diagram presents an outside view of
the system
• The inside behavioral view of a system is
shown by interaction diagrams
http://www.agilemodeling.com/artifacts/sequenceDiagram.htm
Example
Sequence diagram: elements
object
lifetime
activation message
bar
Sequence diagram: flow
place an order
process
validate
Sequence of message sending
if ( payment ok )
if ( not in stock )
deliver
back order
get address
mail to address
Using a SD for workflow
Consistency among diagrams
We can derive the dependencies shown in a class diagram
from the interactions defined in a sequence diagram
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
: Order 1.1 : ok := validate() : Payment
1 : place an order(c)
c : Customer 1.2.2 : get address() p : Product
: Supplier
Sequence and
communication
diagrams
• These two
diagrams are
equivalent
Exercise
• Draw a communication diagram showing
how a customer interacts with a travel
agency, a station and a train to reach
some destination
Use Case
Class diagram
Sequence diagram
• On class diagrams
www.ibm.com/developerworks/rational/library/content/
RationalEdge/sep04/bell/index.html
• On sequence diagrams
www.ibm.com/developerworks/rational/library/3101.html
UML Specification Documents
• OMG, UML Specification v. 1.5, 2003
• OMG, Meta Object Facility 2.0, 2006
• OMG, UML Superstructure 2.1.2, 2007
• OMG, UML Infrastructure 2.1.2, 2007
• Rumbaugh, Jacobson, Booch, The UML Reference
Manual, Addison Wesley, 1999 and 2004 (2nd ed)
References on using UML
• Ambler, The Elements of UML 2.0 Style, Cambridge
University Press, 2005
• 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
Useful sites
• www.uml.org Documents defining the standard
• www.omg.org
• www.agilemodeling.com/essays/umlDiagrams.htm
• softwarestencils.com/uml Images reusable in a graphic editor
• www-306.ibm.com/software/awdtools/rmc/library
• www.cs.gordon.edu/courses/cs211/ATMExample
• opensource.objectsbydesign.com
• www.cragsystems.co.uk/ITMUML/index.htm Online courseware
• www.eclipse.org/modeling/mdt/uml2/docs/articles/Getting_Started_with_UML2/article.html
Tools
• Eclipse + several plugins, like Omondo
• www-01.ibm.com/software/rational/ Rational Rose
• jazz.net New IBM platform
• argouml.tigris.org Argo or Poseidon
• www.borland.com/us/products/together/index.html Borland Together