SYSC 3100 System Analysis and Design

Download Report

Transcript SYSC 3100 System Analysis and Design

SYSC 3100 System Analysis and Design
Class Diagrams:
Defining relationships between classes
Objectives
• To learn how to use the different relationships in a class
diagram. They are:
• Association
• Aggregation (although don’t worry about this one too much)
• composition
• Generalization
• Realization (interfaces)
• Dependency
• To develop software using the Open-Closed Principle.
Associations
• Association: a structural relationship that specifies that objects of one
class are connected to objects of another
– An association describes a group of links (semantic connection
among objects) with common structure and semantics
• Associations represent:
– The possibility of a logical relationship or connection between
objects of one class and objects of another
– If two objects can be linked, their classes have an association
• Mathematically correspond to a set of tuples (Relation)
• Can be implemented in many ways, depending on the programming
language.
• Graphically: a solid line connecting the same or different classes
Associations
Refining the semantics of an association using:
o
o
o
o
o
Basic features
A name
Multiplicities
A role
A navigation
Aggregation and
composition
adornments
o
o
o
o
o
o
Advanced features
Visibilities
Qualifications
Interface specifier
Arity
Association classes
Constraints
Association name
• The name of an association describes the nature of the
relationship
• You can give a direction to a name by providing a
direction triangle that points in the direction you intend to
read the name
Person
Employs
Works-for
Organization
Works-for
Dan Goldin
NASA
Bill Gates
Microsoft
John Smith
Rockwell
...
...
Association multiplicity
• Limit the number of instances of one class that may be
related to an instance of another
• Define the allowed number of links between objects
1
1..*
Class
exactly one
0..*
Class
mandatory (one or more)
Class
many (zero or more)
0..1
Class
optional (zero or one)
2..4, 6..8
Class
numerically specified
Meaning of Multiplicity Constraints
*
Course
teaches
1
Professor
Professor
Dr. Jones
Dr. White
Dr. Brown
Dr. Smith
teaches
Dr. White
CSCI3233
Dr. Smith
CSCI4432
Dr. Brown
SWEN5232
Dr. Brown
SWEN5233
CSCI4432
SWEN5233
CSCI3233
SWEN5232
Course
Analyzing and validating associations
– Many-to-one
• A company has many employees,
• An employee can only work for one company.
– This company will not store data about the moonlighting
activities of employees!
• A company can have zero employees
– E.g. a ‘shell’ company
• It is not possible to be an employee unless you work
for a company
Employee
*
w or ksFor
Company
Example Implementation in Java
Layer
Layer
-layerElements:Set
+elements()
+addElement(le)
+removeElement(le)
1
*
LayerElement
LayerElement
-containedIn:Layer
+getLayer()
+setLayer(l)
Analyzing and validating associations
– Many-to-many
• A secretary can work for many managers
• A manager can have many secretaries
• Secretaries can work in pools
• Managers can have a group of secretaries
• Some managers might have zero secretaries.
• Is it possible for a secretary to have, perhaps
temporarily, zero managers?
Secretary
*
1..* *
supervisor
Manager
Analyzing and validating associations
– One-to-one
• For each company, there is exactly one board of
directors
• A board is the board of only one company
• A company must always have a board
• A board must always be of some company
Company
BoardOfDirectors
Analyzing and validating associations
•Avoid unnecessary one-to-one associations
Avoid this
Person
na me
do this
PersonInfo
Person
ad dres s
na me
ema il
ad dres s
birthd ate
ema il
birthd ate
A more complex example
– A booking is always for exactly one passenger
• no booking with zero passengers
• a booking could never involve more than one
passenger.
– A Passenger can have any number of Bookings
• a passenger could have no bookings at all
• a passenger could have more than one booking
Passenger
*
Booking
*
SpecificFlight
Multiplicity Examples
Professor
name
subject
1
heads
0..1
Department
name
1
teaches
*
Course
title
4..6
studies
1..*
Student
name
number
Multiplicity: Snapshot versus History ?
• What is the scope of multiplicity constraints ?
• Should they cover past, present and future or just present ?
• Answer depends on the context
Man
0..*
married_to
0..*
Woman
=> when a history of marriages is useful (e.g., police)
Man
0..1
married_to
0..1
Woman
=> when only current marital status needed (e.g., bank)
Roles
• Correspond to one end of an association
• Each end of an association may be assigned a role which
serves as its unique identifier
• Provide a way of traversing a binary association from one
object to a set of related objects (more in the section on the
Object Constraint Language)
• Are written next to the association line
Roles
• A Person playing the role of employee is associated with
a Company playing the role of employer.
Person
employer Company
employee
• An Astronaut playing the role of mission specialist
is associated with instances of Experiment.
Astronaut
1..*
conducts
mission_specialist
0..*
Experiment
Reflexive associations
– It is possible for an association to connect a class to itself
successor
* Course
*
*
isMutuallyExclusiveWith
*
prerequisite
For example, use a reflexive associations for a linked
list.
Navigation
UML 2 Syntax
Navigation
A
B
A to B is navigable
B to A is navigable
A
B
A to B is navigable
B to A is not navigable
A
B
A to B is navigable
B to A is undefined
A
B
A to B is undefined
B to A is undefined
A
B
A to B is not navigable
B to A is not navigable
Advert Campaign Example: Associations
Association role
Association
Client
StaffMember
staffName
companyAddress
staffContact
staffNo
staffStartDate
liaises with
companyEmail
companyFax
companyName
companyTelephone
Association name
Direction in which
name should be read
Advert Campaign Example: Links in instance/object diagram
Yellow Partridge:Client
A link is a logical connection
between two objects
FoodCo:Client
Soong Motor Co:Client
Grace Chia:StaffMember
Carlos Moncada:StaffMember
Aggregation
• In a plain association, the two classes are at the same level:
no one more important than the other
• Aggregation: a special form of association between a
whole and its parts
– Relates an assembly class to its component classes
– Represents a “has-a” relationship, meaning that an
object of the whole has objects of the part(s)
• The assembly object propagates instructions to component
objects (access and control through the assembly class)
• Two possibilities:
– Physical: a part cannot be in more than one ‘whole’
– Catalog: a part can be in more than one ‘whole’
Aggregation Examples
Depicted by a diamond at the assembly end
Document
Crew
Team
1..*
*
1..*
4..6
15
Sentence
Astronaut
Person
*
1..*
Word
Aggregation example: graphical interface
Window
*
Pane
TitleBar
0..2
ScrollBar
2
Close Button
Title
Arrow
Indicator
Border
Aggregation - Tree-like Notation
Window
*
Pane
TitleBar
0..2
ScrollBar
2
Close Button
Title
Arrow
Indicator
Border
Recursive Aggregation
Aggregation can be:
– Fixed: the number and types of the parts is fixed
– Variable: the types of parts may vary, but the number of
levels is fixed
– Recursive: the number of levels, and hence parts, is
unlimited
*
Compound
statement
Block
*
Program
Simple
statement
Aggregation
• The meaning of this simple form of aggregation is entirely
conceptual. The open diamond distinguishes the ‘whole’
from the ‘part’, no more, no less.
• This means that simple aggregation does not change the
meaning of navigation across the association between the
whole and the parts, nor does it link the lifetimes of the
whole and its parts.
• Semantics can be very imprecise.
• As a general rule, you can mark an association as an
aggregation when assembly instances owns or controls
access to the component instances.
Advert Campaign Example
Campaign
1
0..*
Advert
Unfilled diamond
signifies aggregation
Composition
• A form of physical aggregation with strong ownership and
coincident lifetime of part with whole:
– Multiplicity at assembly/aggregate end may not exceed 1
(i.e., the component is not shared)
– Distinguished from regular aggregation by means of a
filled diamond
– If the aggregate is destroyed, then the parts are destroyed
as well
Window
scrollbar
Slider
2
title 1
Header
body
1
Panel
Alternative Composition Notations
Window
scrollbar
title 1
2
Slider
Header
Window
body 1
Panel
Window
scrollbar : Slider
title : Header
1
body : Panel
1
2
2
scrollbar
1
title
1
body
Slider
Header
Panel
Sample C++ implementations
• In C++
class Window {
private:
class Slider scrollbar[2];
class Header title;
class Panel body;
};
class Window {
public:
Window() {
scrollbar = new Slider[2];
title = new Header;
body = new Panel;
}
~Panel() {
delete [] scrollbar;
delete title;
delete body;
}
private:
class Slider * scrollbar;
class Header * title;
class Panel * body;
};
Composition and Aggregation
• Student registration example:
Course
1..*
0..*
Student
• Clearly not composition
– Students could be in several courses
– If course is cancelled, students are not destroyed!
Composition and Aggregation (II)
• Advert Campaign example
Campaign
1
1..*
Advert
• This is (probably) composition
Filled diamond signifies composition
– Advert is part of one campaign at a time
– If the campaign is cancelled, the advert is probably
cancelled too.
Propagation
– A mechanism, common in compositions, where an
operation on an aggregate is implemented by having the
aggregate perform that operation on its parts
– At the same time, properties of the parts are often
propagated back to the aggregate
– In the example below, if line segments change in a
polygon, then its surface area may change as a result
– If the polygon is scaled up, then this is propagated to all its
line segments
Polygon
*
LineSegment
Attribute vs. Association: Printing System
Attributes describe objects of a class, Associations are
used to link objects together! (So what’s wrong above?)
Generalization/Specialization
• Definition: a relationship which organizes classes based
on their similarities and differences
• Is implemented with inheritance in object-oriented
languages (more in later sections on *proper*
generalization)
• Sometimes called an “is-a” relationship
• Should mean (but not always the case in practice):
– Objects of the child class may be used anywhere the
parent may appear, but not the reverse
– The child is substitutable for the parent
• Is transitive across an arbitrary number of levels
Generalization/Specialization
• A class may have zero, one or more parents
• Root (base) class: a class with no parent and one or more
children
• Leaf class: a class that has no children
• Simple inheritance: a class has exactly one parent
• Multiple inheritance: a class with more than one parent
(not supported by all programming languages)
– For your own sanity, avoid this anyway.
• Notation: a solid directed line with a large open arrowhead,
pointing to the parent
Simple/Multiple Inheritance
multiple inheritance
InterestBearingItem
InsurableItem
Asset
multiple
inheritance
single
inheritance
BankAccount
CheckingAccount
SavingsAccount
RealEstate
Stock
Security
Bond
Subclasses
• Inherit the attributes, operations, and associations of their
superclass(es)
• Must obey all semantic restrictions of their superclass(es)
• Can override the implementation of an operation
vehicle
size
speed
water vehicle
propeller
land vehicle
wheels
Ancestors/Descendants
•
•
•
•
Multiple generalization levels when multiple discriminators
The discriminator is a label that describes the criteria used in the specialization
The terms ancestor and descendant refer to generalization across multiple levels.
An instance of a class is simultaneously an instance (transitively) of all its
ancestors
Animal
habitat
AquaticAnimal
ty peOf Food
AquaticCarnivore
AquaticHerbivore
LandAnimal
ty peOf Food
LandCarnivore
LandHerbivore
Using Multiple Inheritance
•Avoid duplication of
properties (attributes)
•Increases complexity
AquaticAnimal
AquaticCarnivore
Animal
typeOfFood
habitat
LandAnimal
AquaticHerbivore
Carnivore
LandCarnivore
Herbivore
LandHerbivore
Avoiding unnecessary generalizations
Recording
•No differences in operations
•Inappropriate hierarchy of
classes, which should be
instances
VideoRecod ing
MusicVideo
Recording *
hasCategory
title
artist
JazzRecording
ClassicalRecording
BluesRecording
RockRecording
RecordingCategory
*
subcategory
description
:RecordingCategory
:RecordingCategory
video
audio
subcategory
AudioRecording
subcategory
subcategory
subcategory
Improved class diagram,
with a corresponding
instance/object diagram
subcategory
:RecordingCategory
:RecordingCategory :RecordingCategory
:RecordingCategory :RecordingCategory
music video
jazz
blues
classical
rock
:Recording
:Recording
9th Symphony
Beethoven
Let it be
The Beatles
Generalization Constraints
Constraints can be used to describe the relationship between a
class and its subclasses. The generalization can be:
complete
// all subclasses have been specified (no more are
expected)
incomplete
// some subclasses have been specified but it is
known that others exist
disjoint
// objects of the parent may have no more than one
of the children as a type e.g. class Person can
be specialized into disjoint classes Man and
Woman.
overlapping // objects of the parent may have more than one of
the children as a type e.g. class Vehicle can be
specialized into overlapping subclasses
LanVehicle and WaterVehicle (an
amphibious vehicle is both)
disjoint and overlapping applies only to multiple inheritance.
Complete Specialization
Person
{complete}
Person
Male
Person
Female
Person
{complete}
Male
Person
...
ellipses indicate that other
specializations are known to
exist but are not shown
Incomplete Specialization
indicates that defined
model elements are not
shown
Fruit
...
Apple
{incomplete}
indicates that other
elements are know to
exist but have not been
defined
Golden
Delicious
Cox
Macintosh
Overlapping Example
Person
1
*
UniversityMember
{overlapping}
Faculty
Student
Instructor
Staff
Advert Campaign Example
• Two types of staff:
Creative
Have qualifications recorded
Can be client contact for campaign
Bonus based on campaigns they
have worked on
Admin
Qualifications are not recorded
Not associated with campaigns
Bonus not based on campaign profits
Using
Inheritance
StaffMember
{abstract}
staffName
staffNo
staffStartDate
calculate Bonus( )
assignNewStaffGrade( )
getStaffDetails( )
AdminStaff
calculateBonus( )
CreativeStaff
qualification
calculateBonus( )
assignStaffContact( )
Meaning of Roles
• Roles can be thought of as a shorthand form of
specialization and can be changed as such if needed
conducts
1..*
mission_specialist
Astronaut
0..*
Experiment
Astronaut
1..*
Mission_Specialist
Astronaut
Shepherd
Armstrong
conducts
1..*
Experiment
Experiment
Aldrin
Frogs
Spawning
Collins
Mission
Specialist
Crystal
Formation
Abstract, Root, Leaf, and Polymorphic Elements
• Abstract class: may not have any direct instance
– The name of the class is in italics (same thing for abstract
operations)
– Or The property {abstract} is written below the class’s name
– A class that may have instance(s) is a concrete class
• Leaf class / operation: may have no children / redefinitions
– The property {leaf} is written below the class’s name
– The property {leaf} is written after a leaf operation
• Root class: may have no parent
– The property {root} is written below the class’s name
• Polymorphic operation: contrary to leaf operations, may have several
implementations in an inheritance hierarchy (default)
Abstract, Root, Leaf, and Polymorphic Elements
Icon
{root}
origin: Point
RectanglarIcon
base class
display()
getId(): Int {leaf}
height: Int
width: Int
abstract operation
concrete operation
abstract class
Button
display()
concrete class
ArbitraryIcon
edge: LineCollection
OKButton
{leaf}
display()
isInside(p: Point): Boolean
leaf class
polymorphic
operation
Avoiding having instances change class
– An instance should never need
to change class during
execution (complex operation)
– Player-Role pattern
AttendanceRole
Student
attendance
FullTimeStudent
Student
LevelRo le
attendance
FullTimeStu dent
PartTimeStudent
level
PartTimeStudent
Grad uateStuden t
UndergraduateStudent
Avoiding multiple inheritance
Animal
typeOfFood
habitat
AquaticAnimal
AquaticCarnivore
LandAnimal
AquaticHerbivore
Animal
typeOf Food
Carnivore
Herbivore
Omnivore
Carnivore
LandCarnivore
0..2
Herbivore
LandHerbivore
HabitatRole
habitat
AquaticAnimal
LandAnimal
Associations versus generalizations in instance
diagrams
– Associations describe the relationships that will exist
between instances at run time.
• When you show an instance diagram generated from a
class diagram, there will be an instance of both classes
joined by an association
– Generalizations describe relationships between classes in
class diagrams.
• They do not appear in instance diagrams at all.
• An instance of any class should also be considered to
be an instance of each of that class’ superclasses
Dependency
•
•
•
•
A dependency is a using relationship that state that a change in
specification of one thing may affect another thing that uses it, but not
necessarily the reverse
Usually, the used class is the type of an argument in the signature of an
operation or a local variable in the using class.
Graphically: a dashed directed line, directed to the thing being depended
on.
Refining dependencies with stereotypes
Window
Event
•
Interface Relationships
You can show that an element realizes an interface in two ways:
– As a simple form in which the interface and its realization relationship are
rendered as a line between the class box and a small circle.
– Or you can use the expanded form in which an interface is rendered as a
stereotyped classrequired interface
provided interface
Target
Observer
TargetTracker
Observer
realization (simple form)
Java::Util::Observable
usage
requires
dependency
interface definition
Target
id
currentPosition
setPosition()
setVelocity()
expectedPosition()
«interface»
Observer
TargetTracker
update()
realization (provides dependency)
Interface - Example
• The component Ledger provides (realizes) three interfaces:
IUnknown, Iledger, and IReports. These are exported to other
components to build on.
• Ledger also requires (uses) two interfaces: IStreaming and
ITransaction.
«interface»
IUnknown
QueryInterface():HRESULT
AddRef():ULONG
Release():ULONG
«interface»
ITransaction
start()
perfromAction()
commit()
rollback()
Exceptions
failure
ILedger
Ledger
IReports
IStreaming
Interfaces versus Superclasses
• An interface describes a portion of the visible behaviour
of a set of objects.
– An interface is similar to a class, except it lacks
instance variables and implemented methods
Person
«interface»
Cashier
Machine
withdraw
deposit
Employee
Person
Cashier
ATM
Employee
Machine
Cashier
ATM
Open Closed Principle (OCP)
• Both interfaces and Abstract classes can be used to implement this
important principles.
• “All systems change during their life-cycles. This must be born in
mind when developing system expected to last longer than the first
version”, Ivar Jacobsen
• Software entities (classes modules, functions, etc) should be open for
extension but closed for modification, Bertrand Meyer 1988
• The Open-Closed Principle encourages software developers to design
and write code in a fashion that adding new functionality would
involve minimal changes to existing code.
– most changes will be handled as new methods and new classes
– designs following this principle would result in resilient code
which does not break on addition of new functionality
Abstraction and OCP
Client is closed to changes
in implementation of Server
Client is open for extension
through new Server
implementations
Without AbsServer the Client
is open to changes in Server
Example
Discussion
• Strategy is Open-Closed Principle because implementing a new
Strategy does not require a change to the Player Class.
– This class is essentially closed for modification
– However, because we can pass in an object that implements
ComputerStrategy, the class is open for extension
• Extending Player (the client) only requires new modules (classes) be
written that implement ComputerStrategy,
– There are no changes to the existing Player
Summary
• Associations:
– Used to connect objects together. They are not
attributes.
– Aggregation, who cares?
– Composition, parent dies, children do too.
• Generalization (superclass). Specialization (subclass).
– Avoid: multiple inheritance (use role player pattern)
– Over-specialization (use attributes)
• Open-Closed principle: design to interfaces.