63
SYSC 3100 System Analysis and Design Class Diagrams: Defining relationships between classes

SYSC 3100 System Analysis and Design Class Diagrams: Defining relationships between classes

  • View
    227

  • Download
    2

Embed Size (px)

Citation preview

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:

Basic featureso A nameo Multiplicities o A roleo A navigationo Aggregation and

composition adornments

Advanced featureso Visibilitieso Qualificationso Interface specifiero Arityo Association classeso 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

Dan Goldin NASA

Bill Gates Microsoft

John Smith Rockwell

... ...

Works-forPerson

Organization

Works-forEmploys

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

Class

Class

Class

Class

Class

many (zero or more)

optional (zero or one)

mandatory (one or more)

numerically specified

1..*

2..4, 6..8

exactly one

0..*

0..1

1

Meaning of Multiplicity Constraints

Course1teaches

Professor*

Professor

Course

SWEN5232

CSCI3233SWEN5233

Dr. Smith

Dr. WhiteDr. Brown

Dr. Jones

CSCI4432

Dr. White CSCI3233

Dr. Smith CSCI4432

Dr. Brown SWEN5232

teaches

Dr. Brown SWEN5233

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

* worksForEmployee Company

Example Implementation in Java

Layer LayerElement1 *

LayerElement

-containedIn:Layer+getLayer()+setLayer(l)

Layer

-layerElements:Set+elements()+addElement(le)+removeElement(le)

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?

*

supervisor

*****1..*Secretary 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 do this

Person

nameaddressemailbirthdate

Person

name

PersonInfo

addressemailbirthdate

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 SpecificFlightBooking

Multiplicity Examples

Professornamesubject

heads

Course

title

teaches

1

1..*

*

Department

name0..11

studiesStudent

namenumber

4..6

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

WomanManmarried_to

WomanMan married_to

=> when a history of marriages is useful (e.g., police)

=> when only current marital status needed (e.g., bank)

0..* 0..*

0..1 0..1

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

conducts

mission_specialist

0..*1..*

Person Companyemployee employer

Astronaut Experiment

• A Person playing the role of employee is associated with a Company playing the role of employer.

• An Astronaut playing the role of mission specialist is associated with instances of Experiment.

Reflexive associations

–It is possible for an association to connect a class to itself

Course *isMutuallyExclusiveWith

*

*

prerequisite

successor *

For example, use a reflexive associations for a linked list.

NavigationUML 2 Syntax Navigation

A to B is navigableB to A is navigable

A to B is navigableB to A is not navigable

A to B is navigableB to A is undefined

A to B is undefinedB to A is undefined

A to B is not navigableB to A is not navigable

A B

BA

BA

BA

BA

Advert Campaign Example: Associations

StaffMember

staffName

staffNo

staffStartDate

Client

companyAddress

companyEmail

companyFax

companyName

companyTelephone

liaises with

staffContact

Association role Association

Association nameDirection in which name should be read

Advert Campaign Example: Links in instance/object diagram

FoodCo:Client

Yellow Partridge:Client

Soong Motor Co:Client

Grace Chia:StaffMember

Carlos Moncada:StaffMember

A link is a logical connection between two objects

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

Document Sentence Word1..*

Crew Astronaut4..6*

*1..*1..*

Team Person15

Depicted by a diamond at the assembly end

Aggregation example: graphical interface

Window

PaneTitleBar ScrollBar Border

Close Button Title Arrow Indicator

*

2

0..2

Aggregation - Tree-like Notation

Window

PaneTitleBar ScrollBar Border

Close Button Title Arrow Indicator

*

2

0..2

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

Block

Compoundstatement

Simplestatement

Program* *

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 Advert0..*1

Unfilled diamond signifies aggregation

title

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 wellWindow

HeaderSlider Panel

scrollbar body 112

Alternative Composition Notations

title

Window

HeaderSlider Panel

scrollbar body 112

Window

scrollbar : Slider

title : Header

body : Panel

1

1

2

Window

Header

Panel

Slider

title

scrollbar

body

1

1

2

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:

• Clearly not composition– Students could be in several courses– If course is cancelled, students are not destroyed!

Course Student0..*1..*

Composition and Aggregation (II)

• Advert Campaign example

• This is (probably) composition– Advert is part of one campaign at a time– If the campaign is cancelled, the advert is probably

cancelled too.

Campaign Advert1..*1

Filled diamond signifies composition

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

****** LineSegmentPolygon

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

InterestBearingItem InsurableItem

BankAccount

Asset

CheckingAccount SavingsAccount

RealEstate Security

Stock Bond

Simple/Multiple Inheritance

multipleinheritance

multiple inheritance

singleinheritance

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

vehiclesizespeed

land vehicle

wheels

water vehicle

propeller

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

ancestorsAnimal

habitat

LandAnimalAquaticAnimal

AquaticCarnivore AquaticHerbivore LandCarnivore LandHerbivore

typeOfFood typeOfFood

Using Multiple Inheritance

Animal

habitat typeOfFood

HerbivoreCarnivoreLandAnimalAquaticAnimal

AquaticCarnivore AquaticHerbivore LandCarnivore LandHerbivore

• Avoid duplication of properties (attributes)

• Increases complexity

Avoiding unnecessary generalizations

RockRecordingBluesRecordingClassicalRecordingJazzRecordingMusicVideo

VideoRecoding AudioRecording

Recording

• No differences in operations• Inappropriate hierarchy ofclasses, which should be instances

Improved class diagram,with a correspondinginstance/object diagram

rockbluesclassicaljazzmusic video

video audio

RecordingCategory*subcategorydescription

Recording *hasCategory

subcategory subcategorysubcategorysubcategorysubcategory

:RecordingCategory :RecordingCategory

:RecordingCategory :RecordingCategory :RecordingCategory :RecordingCategory:RecordingCategory

9th Symphony

:Recording

Let it be

:Recording

The BeatlesBeethoven

titleartist

Generalization ConstraintsConstraints 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 existdisjoint // 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

MalePerson

FemalePerson

{complete}

Person

MalePerson

{complete}

ellipses indicate that other specializations are known to exist but are not shown

...

Incomplete Specialization

Fruit

Macintosh

Apple

Cox

...

GoldenDelicious

{incomplete}

indicates that defined model elements are not shown

indicates that other elements are know to exist but have not been defined

Overlapping Example

Faculty Student Staff

Instructor

UniversityMemberPerson*1

{overlapping}

Advert Campaign Example

• Two types of staff:

Have qualifications recordedCan be client contact for campaignBonus based on campaigns they have worked on

Creative

AdminQualifications are not recordedNot associated with campaignsBonus not based on campaign profits

Using Inheritance

calculateBonus( )

StaffMember{abstract}

staffNamestaffNostaffStartDatecalculate Bonus( )assignNewStaffGrade( )getStaffDetails( )

CreativeStaff

qualification

assignStaffContact( )

AdminStaff

calculateBonus( )

Meaning of Roles

• Roles can be thought of as a shorthand form of specialization and can be changed as such if needed

Experiment

Astronaut

conducts 1..*1..*Mission_Specialist

Astronaut

Shepherd

CollinsArmstrong

Aldrin

MissionSpecialist

Experiment

Frogs Spawning

CrystalFormation

conducts

mission_specialist0..*1..*Astronaut Experiment

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

display()getId(): Int {leaf}

RectanglarIcon

height: Intwidth: Int

ArbitraryIcon

edge: LineCollection

isInside(p: Point): Boolean

Button

display() OKButton{leaf}

display()

base class

abstract class

abstract operation

concrete operation

concrete class

leaf class polymorphicoperation

Avoiding having instances change class

– An instance should never need to change class during execution (complex operation)

– Player-Role pattern

Student

attendance

PartTimeStudentFullTimeStudent

LevelRole

attendance

PartTimeStudentFullTimeStudent UndergraduateStudentGraduateStudent

level

StudentAttendanceRole

Avoiding multiple inheritance

Animal HabitatRole

habitattypeOfFood

OmnivoreHerbivore LandAnimalAquaticAnimal

0..2

Carnivore

Animal

habitat typeOfFood

HerbivoreCarnivoreLandAnimalAquaticAnimal

AquaticCarnivore AquaticHerbivore LandCarnivore LandHerbivore

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

WindowEvent

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 class

Target TargetTrackerObserver Observer

required interfaceprovided interface

realization (simple form)

Java::Util::Observable

TargetidcurrentPositionsetPosition()setVelocity()expectedPosition()

«interface»Observer

update()TargetTracker

usagerequires

dependency

realization (provides dependency)

interface definition

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():HRESULTAddRef():ULONGRelease():ULONG

Ledger

«interface»ITransaction

start()perfromAction()commit()rollback()

Exceptionsfailure

ILedger

IReports IStreaming

Interfaces versus Superclasses

«interface»Cashier

withdrawdeposit

Machine

ATMEmployee

Person Machine

ATMEmployee

Person

Cashier Cashier

• 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

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 changesin implementation of Server

Client is open for extensionthrough new Serverimplementations

Without AbsServer the Clientis 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.