63
Devon M. Simmonds University of North Carolina, Wilmington CSC450 Software Engineering Introduction to UML Class Diagrams

Devon M. Simmonds University of North Carolina, Wilmington CSC450 Software Engineering Introduction to UML Class Diagrams

Embed Size (px)

Citation preview

Devon M. SimmondsUniversity of North Carolina, Wilmington

CSC450Software

Engineering

Introduction to UML Class Diagrams

Objectives

Introduce basic class diagram constructs Introduce UML relationships

Generalization Association

Aggregation/composition Dependency

Interfaces

What is a class? A class is a description of a set of

objects that share the same properties attributes Operations

Java classpublic class Student {

String id;Address addr;

int graduate (String semester)

}

StudentId:IntegerAddr:String

graduate(semester:String):int

UML class

Structure of a class

A class has the following structure: Name compartment (mandatory) Attributes compartment (optional) Operations compartment (optional)

Every class must have a distinguishing name.

An object is an instance of a class An object of a class must have

values associated with each attribute of the class

Name

attributes

operations

StudentId:IntegerAddr:String

graduate(semester:String):int

johnWayne:StudentId = 2007Addr = “Wild Wild West”

Class Notation

Rectangle

heightwidth

getArearesize

Rectangle

heightwidth

Rectangle

getArea

resize

Rectangle

name

attributes

operations

attributesoperations

Attributes

An attribute is a named property. Each class instance associates value(s) with each attribute of a concept.

What should be an attribute? Properties with types that we want to treat as

primitive are modeled as attributes Connections to other classes are to be represented as

associations, not attributes.

Window

size:Areavisibility:Booleandisplay()hide()

Operations

An operation is a procedure defined in a class. Each operation has a signature and a

specification of its behavior. Signature: operation name, a list of argument types

and the result type. operationName(parameterName: parameterType …):

returnType

Specification is expressed in terms of pre-and postconditions (the Object Constraint Language is used for this purpose)

Operations II

A method is the implementation of an operation.

Classes in requirements and domain models DO NOT NEED to contain operations Rationale: in most cases, distributing

operations across classes requires making design-level decision.

Objectives

Introduce basic class diagram constructs Introduce UML relationships

Association Aggregation/composition

Generalization Dependency

UML Interfaces

Modeling Static Class Relationships

Association Aggregation/composition

Generalization Dependency

10

Associations

Associations represent conceptual relationships among problem concepts or classes.

Association properties include Multiplicity Role Constraints

Associations

works-for 4Employee Company

Association name

-"direction reading arrow"-it has no meaning except to indicate direction of reading the association label-often excluded

1 1

multiplicity

Multiplicity

zero or more;"many"

one or more

one to forty

exactly five

exactly three,five or eight

3, 5, 8

One instance of aCustomer may be rentingzero or more Videos.

One instance of a Videomay be being rented byzero or one Customers.

Customer

Video

Rents 6

*

0..1

5

1..40

1..*

* Student

Student

Student

Student

Student

Association Multiplicity Examples

Employee*0..1Office

*Employee Company

* *****1..*Secretary Manager

0,3..8 ******Person BoardOfDirectors

Company BoardOfDirectors

Labelling associations Each association can be labelled with a

name that gives insight into the meaning of the association

*

supervisor

*****1..*

* worksFor

*allocatedTo0..1

boardMember

0,3..8 ******

Employee

Secretary

Office

Person

Company

Employee Company

Manager

BoardOfDirectors

BoardOfDirectors

Association Roles

When a class is part of an association it plays a role in the relationship.

You can name the role that a class plays in an association by placing the name at the class’s association end.

Formally, a class role is the set of objects that are linked via the association.

ProjectPerson

project leader

project member

managed project

assignedproject

class roles

1 0..1

*1..*

Analyzing and validating associations

Many-to-one A company has many employees, An employee can only work for one

company. 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

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

Do Not Use Attributes To Relate Concepts

Video

...

Rents 1 1.. *Customer

...Better

Video

renter : Customer

Customer

rentedVideos: List of VideoWorse

Reflexive associations It is possible for an association to

connect a class to itself

Course *isMutuallyExclusiveWith

*

*

prerequisite

successor *

Navigability

One can indicate that an object “knows about” another object it is linked to by using navigation arrows on associations In UML 2.0 one can also explicitly

show that one object does not know about the objects it is linked to.

• The top pair AB shows a binary association with two navigable ends.• The second pair CD shows a binary association with two non-navigable ends.• The third pair EF shows a binary association with unspecified navigability.• The fourth pair GH shows a binary association with one end navigable and the other

non-navigable.• The fifth pair IJ shows a binary association with one end navigable and the other

having unspecified navigability.

The constructs in diagrams 1, 2, and 4 are new to UML 2.0 and thus are most likely not supported by UML tools as yet.

Actions versus associations

A common mistake is to represent actions as if they were associations

*

LibraryPatron

borrow Loan

borrowedDatedueDatereturnedDate

Bad, due to the use of associations that are

actions

****

*

return

CollectionItem

*

*

LibraryPatron

CollectionItem

*

*

Better: The borrow operation creates a Loan and the return operation sets the

returnedDate

What is a Class Diagram?

A class diagram describes a structure of classes

Key Question: What are the objects of interest in the problem/solution space? their properties (in terms of attributes

and operations)? their relationships?

An example of a Class Diagram description of problem concepts

The above is part of a domain model for a video rental system

Video

ID

Stocks 4

Rents 4

Rents-from 4

0..1*

1 *1*

VideoStore

addressnamephoneNumber

Customer

addressnamephoneNumber

HeadOffice branchOffice*1..2

Objects and Links

An object is an instance of a class A link is an instance of an

association

Can you draw a valid object diagram for this class diagram?

Video

ID

Stocks 4

Rents 4

Rents-from 4

0..1*

1 *1*

VideoStore

addressnamephoneNumber

Customer

addressnamephoneNumber

HeadOffice branchOffice*1..2

Association: Model to Implementation

Class Student { Course enrolls[4];}

Class Course {Student istakenby[];

}

Student Courseenrollsistakenby

* 4

29

Association: Model to Implementation

Class Student { Course enrolls[4];}

Student Courseenrollshas

* 4

30

Modeling Static Class Relationships

Association Aggregation/composition

Generalization Dependency

31

Aggregation

Aggregation is a special form of association reflect whole-part relationships

The whole delegates responsibilities to its parts the parts are subordinate to the

whole This is unlike associations in which

classes have equal status

UML Forms of Aggregation

Composition (strong aggregation) parts are existent-dependent on the

whole parts are generated at the same time,

before, or after the whole is created (depending on cardinality at whole end) and parts are deleted before or at the same time the whole dies

multiplicity at whole end must be 1 or 0..1

(weak) Aggregation

Composition – black diamond notation

Window

scrollbar title body

HeaderPanel

21 1

Slider

1

11

OO Relationships: Composition

Class W

Class P1 Class P2

Composition: expresses a relationship among instances of related classes. It is a specific kind of Whole-Part relationship.

Whole Class

Part Classes

Automobile

Engine Transmission

Example

[From Dr.David A. Workman]

It expresses a relationship where an instance of the Whole-class has the responsibility to create and initialize instances of each Part-class.

It may also be used to express a relationship where instancesof the Part-classes have privileged access or visibility tocertain attributes and/or behaviors defined by theWhole-class.

Composition should also be used to express relationship where instances of the Whole-class have exclusive access to and control of instances of the Part-classes.

Composition should be used to express a relationship wherethe behavior of Part instances is undefined without beingrelated to an instance of the Whole. And, conversely, thebehavior of the Whole is ill-defined or incomplete if one or more of the Part instances are undefined.

35

OO Relationships: Aggregation

Class C

Class E1 Class E2

AGGREGATION

Aggregation: expresses a relationship among instances of related classes. It is a specific kind of Container-Containee relationship.

It expresses a relationship where an instance of the Container-class has the responsibility to hold and maintain instances of each Containee-class that have been createdoutside the auspices of the Container-class.

Aggregation should be used to express a more informalrelationship than composition expresses. That is, it is anappropriate relationship where the Container and its Containees can be manipulated independently.

Aggregation is appropriate when Container and Containees have no special access privileges to each other.

Container Class

Containee Classes

Bag

Apples Milk

Example

[From Dr.David A. Workman]36

Aggregation vs. Composition

• Composition is really a strong form of aggregation • components have only one owner • components cannot exist independent of their owner • components live or die with their owner

e.g. Each car has an engine that can not be shared with other cars.

• Aggregations may form "part of" the aggregate, but may not be essential to it. They may also exist independent of the aggregate. e.g. Apples may exist independent of the bag.

37

Modeling Static Class Relationships

Association Aggregation/composition

Generalization Dependency

38

Generalization/Specialization

A generalization (or specialization) is a relationship between a general concept and its specializations. Objects of specializations can be used

anywhere an object of a generalization is expected (but not vice versa).

Example: Polygon and Ellipse are specializations of Shape

Generalization

Shape

SplineEllipsePolygon

Shape

SplineEllipsePolygon

Shared Target Style

Separate Target Style

. . .

. . .

Rendering Generalizations Generalization is rendered as a solid

directed line with a large open arrowhead. Arrowhead points towards generalization

A discriminator can be used to identify the nature of specializations

Generalization

Fig. 3-48, UML Notation Guide

Vehicle

WindPoweredVehicle

MotorPoweredVehicle

LandVehicle

WaterVehicle

venue

venuepowerpower

SailboatTruck

{overlapping} {overlapping}

An example (generalization)

*

supervisor

RegularFlight

timeflightNumber

*

******

PassengerRole

******

******

******

SpecificFlight

date

Person

nameidNumber

0..20..20..20..20..20..2

EmployeeRole

jobFunction

Booking

seatNumber

PersonRole

Object Diagram - Example

Person Organization

0..1 parent

Organismlocation

* children

Engineering:OrganizationLocation=“chicago”

Apps:Organization

location=“Wilmington”

Tools:Organization

Location=“chicago”

don:Personlocation=“Raleigh”

charlene:Personlocation=“denver”

manager employee

43

Association end constraints

Binary and N-ary Associations

A binary association relates two classes.

An n-ary association relates n (n > 2) classes.

N-ary associations can often be modeled as binary associations.

Can you interpret the following?

Class Diagram Exercise Create a use case diagram and a class diagram

using the problem description below. The BirdCage Corporation needs software to aid the management of

its business. The corporation builds its business around domestic birds. BirdCage arranges its business around different services with each service being managed by a different company making BirdCage a group of companies. Companies are divided into departments. Services include veterinary services, safekeeping of birds, bird calisthenics and a bird competitions service. In order to streamline its business, BirdCage classifies the veterinary and safekeeping services as medical services. The other two services are regarded as entertainment services. In the future the company hopes to add a number of “Nutritional” services to address the production and sales of food for birds. The corporation classifies birds as either exotic or non-exotic. BirdCage does not provide entertainment services for exotic birds. Owls and crows are non-exotic birds, while macaws, cockatoos and green quakers are exotic. BirdCage seeks to maintain a minimum stock of at least 10 of each type of exotic bird.

Modeling Static Class Relationships

Association Aggregation/composition

Generalization Dependency

48

Dependencies in UML

A dependency is a client-server relationship between model elements.

A dependency is shown as a dashed arrow between two model elements. The server is at the arrowhead. The arrow may be labeled with an

optional stereotype.49

Dependencies Notation in UML

50

Realization Dependencies

51

Usage Dependencies

52

Objectives

Introduce basic class diagram constructs Introduce UML relationships

Generalization Association

Aggregation/composition Dependency

UML Interfaces

Interfaces in UML

An interface is a named collection of operations that represent the services provided by a class or component.

Interfaces do not typically have attributes.

Interfaces do not provide implementations for their operations. 54

Example of an interface

Interface

operation1( ) : Type1

operation2( ) : Type2

operation3( ) : Type3

operation4( ) : Type4

operation5( ) : Type5

55

UML Notation for Interfaces

An interface may be identified using the <<interface>> keyword preceding the name of the interface.

Classes that use the interface can have two types of relationships or dependencies

Interface realization Usage

Realization DependencyUsage Dependency

56

UML Notation for Interfaces

Interface realization means ProximitySensor implements the operations defined by ISensor.

ISensor is called a provided interface for ProximitySensor.

Interface usage means TheAlarm uses the operations defined by ISensor.

ISensor is called a requiredinterface for TheAlarm.

Interface RealizationUsage

57

Interfaces: Dependency

Required InterfaceUsage Dependency

Provided InterfaceRealization Dependency

58

Interfaces: Dependency

ISensor

Provided InterfaceRealization Dependency

Required InterfaceUsage Dependency

“Ball-and-socket” notation

59

What does this model mean?

IAlarm is a provided interface for ISensor.

ISensor is a provided interface for IAlarm .

60

What does this model mean?

IBuzzer is a provided interface for IAlarm .

…61

Summary

In this lecture we: Introduced basic class diagram

constructs Relationships in UML

Association/aggregation/composition/dependency

UML Interfaces

What’s coming next class?

______________________Devon M. Simmonds

Computer Science Department

University of North Carolina Wilmington

_____________________________________________________________

Qu es ti ons?

63